举例讲解Python面相对象编程中对象的属性与类的方法


Posted in Python onJanuary 19, 2016

python 对象的属性
进入正题,来看一个实例来了解python中类,对象中公有属性,私有属性及局部变量,全局变量的区别.

root@10.1.6.200:~# cat object.py
#!/usr/bin/env python
#coding:utf8
 
class Dave():
  var1 = "class atribute,public atrribute var1" #类属性,公有属性var1
  __var2 = "class self atribute __var2"  #类的私有属性__var2
 
  def fun(self):
    self.var2 = "object public atrribute var2" #对象的公有属性var2
    self.__var3 = "object self atrribute __var3" #对象的私有属性__var3
    var4 = "Function of the local variable var4" #函数fun的局部变量
   
  def other(self):
    print self.__var3

根据上面代码后面加入以下代码可以实例化一个对象及获取类公有属性.

he = Dave()    #实例化一个对象he
print he.var1   #从实例中获取类的公有属性
print Dave.var1  #直接从类中获取公有属性
root@10.1.6.200:~# ./object.py
class atribute,public atrribute var1
class atribute,public atrribute var1

类的私有属性不能被类或对象直接调用

he = Dave()
print Dave.__var2
print he.__var2
root@10.1.6.200:~# ./object.py
Traceback (most recent call last):
 File "./object.py", line 19, in <module>
  print Dave.__var2
AttributeError: class Dave has no attribute '__var2'

但可以通过方法间接调用.

class Dave():
  var1 = "class atribute,public atrribute var1" #类属性,公有属性var1
  __var2 = "class self atribute __var2"  #类的私有属性__var2
   
  def other(self):
    print Dave.__var2   
 
he = Dave()
he.other()
root@10.1.6.200:~# ./object.py
class self atribute __var2

获取类方法中的对象的公有属性,需要先通过对象执行类中的方法.并通过对象调用该属性.

he = Dave()
liu = Dave()
he.fun()
print he.var2
print liu.var2
root@10.1.6.200:~# ./object.py
object public atrribute var2
Traceback (most recent call last): <span></span>       #对象liu由于没有调用fun方法所有就没有该属性.
File "./object.py", line 20, in <module>
  print liu.var2
AttributeError: Dave instance has no attribute 'var2'

对象的私有属性和类的私有属性类似,也不能被类或对象直接调用

he = Dave()
he.fun()
print he.__var3
root@10.1.6.200:~# ./object.py
Traceback (most recent call last):
 File "./object.py", line 18, in <module>
  print he.__var3
AttributeError: Dave instance has no attribute '__var3'

局部变量也不能被对象直接调用,可以在函数内部使用.

he = Dave()
he.fun()
print he.var4
root@10.1.6.200:~# ./object.py

Traceback (most recent call last):
 File "./object.py", line 18, in <module>
  print he.var4
AttributeError: Dave instance has no attribute 'var4'
def fun(self):
    self.var2 = "object public atrribute var2" #对象的公有属性var2
    self.__var3 = "object self atrribute __var3" #对象的私有属性__var3
    var4 = "Function of the local variable var4" #函数fun的局部变量
    print var4       #可以在函数内部直接打印,只在该函数内有用
    print self.__var3
 
he = Dave()
he.fun()
root@10.1.6.200:~# ./object.py
Function of the local variable var4
object self atrribute __var3

那么var4和self._var3有什么区别呢.目前看2个都在外部使用不了.下面在定义一个函数other调用.

def fun(self):
    self.var2 = "object public atrribute var2" #对象的公有属性var2
    self.__var3 = "object self atrribute __var3" #对象的私有属性__var3
    var4 = "Function of the local variable var4" #函数fun的局部变量
    print var4       #一个函数的局部变量在另外一个函数是访问不到的
    print self.__var3
   
  def other(self):
    print var4
    print self.__var3
 
he = Dave()
he.fun()
print "#"*100
he.other()
root@10.1.6.200:~# ./object.py
Function of the local variable var4
object self atrribute __var3
####################################################################################################
Traceback (most recent call last):   #会认为var4是全局变量打印.定义全局变量可在class 头加入 var4 = "global"
 File "./object.py", line 22, in <module>
  he.other()
 File "./object.py", line 16, in other
  print var4
NameError: global name 'var4' is not defined
#!/usr/bin/env python
#coding:utf8
var4 = "global"            #定义var4为全局变量
class Dave():
  var1 = "class atribute,public atrribute var1" #类属性,公有属性var1
  __var2 = "class self atribute __var2"  #类的私有属性__var2
 
  def fun(self):
    self.var2 = "object public atrribute var2" #对象的公有属性var2
    self.__var3 = "object self atrribute __var3" #对象的私有属性__var3
    var4 = "Function of the local variable var4" #函数fun的局部变量
    print var4
    print self.__var3
   
  def other(self):
    print var4
    print self.__var3       #可调用私有属性,前提是先调用fun
 
he = Dave()
he.fun()
print "#"*100
he.other()
root@10.1.6.200:~# ./object.py
Function of the local variable var4
object self atrribute __var3
####################################################################################################
global
object self atrribute __var3

python 类的方法
python类中的方法:公有方法,私有方法,类方法,静态方法.

下面通过一个实例了解它们之间的区别:

#!/usr/bin/env python
#coding:utf8
class Dave():
  name = "python"
 
  def fun1(self):        #定义公有方法
    print self.name
    print "i am public method"
 
  def __fun2(self):       #定义私有方法
    print self.name
    print "i am self method"

先来看公有方法和私有方法,加入以下代码输出

root@10.1.6.200:~# ./method.py    #直接调用对象公有方法没有问题
python
i am public method

私有方法和私有属性一样是被保护起来,不能直接调用对象的私有方法,但可以间接调用.

#!/usr/bin/env python
#coding:utf8
class Dave():
  name = "python"
 
  def fun1(self):        #定义公有方法
    print self.name
    print "i am public method"
    self.__fun2()
 
  def __fun2(self):       #定义私有方法
    print self.name
    print "i am self method"
 
he = Dave()
he.fun1()
root@10.1.6.200:~# ./method.py
python
i am public method
python
i am self method

公有属性是可以被类调用,但是公有方法是不可以被类直接调用.需要实例化对象调用.如果想一个方法被类直接调用的话,就需要转换,变成一个类方法.变成类方法有2种,比较简单的可以加装饰器.

@classmethod
  def classFun(self):      #定义类方法
    print self.name
    print "i am class method"
 
Dave.classFun()
root@10.1.6.200:~# ./method.py
python
i am class method

另一个方法比较麻烦,需要定义一个新的函数,以及使用classmethod方法转换函数为类方法.当然调用也需要使用新的该函数名字.

def classFun(self):      #定义类方法
    print self.name
    print "i am class method"
 
  classnewFun = classmethod(classFun)
 
 
Dave.classnewFun()       #被转换后的是一个类方法,原来classfun还是一个普通方法
root@10.1.6.200:~# ./method.py
python
i am class method

静态方法在使用中和类方法一样,也是为了让类中直接调用,区别定义时不加self.

@staticmethod
  def staticFun():       #d定义静态方法
    print Dave.name #注意不加self,直接打name也不行,会认为调用全局变量,需要使用类型加属性.
    print "i am static method"
 
Dave.staticFun()
oot@10.1.6.200:~# ./method.py
python
i am static method

同样也可以通过一个函数调用

def staticfun():       #定义静态方法
    print Dave.name
    print "i am static method"
 
  staticnewFun = staticmethod(staticFun)
 
Dave.staticnewFun()
root@10.1.6.200:~# ./method.py
python
i am static method
Python 相关文章推荐
python条件和循环的使用方法
Nov 01 Python
python通过wxPython打开一个音频文件并播放的方法
Mar 25 Python
玩转python爬虫之爬取糗事百科段子
Feb 17 Python
Python实现将不规范的英文名字首字母大写
Nov 15 Python
Python3一行代码实现图片文字识别的示例
Jan 15 Python
Python模块WSGI使用详解
Feb 02 Python
超简单使用Python换脸实例
Mar 27 Python
如何实现在jupyter notebook中播放视频(不停地展示图片)
Apr 23 Python
python中urllib.request和requests的使用及区别详解
May 05 Python
使用Keras 实现查看model weights .h5 文件的内容
Jun 09 Python
python神经网络编程之手写数字识别
May 08 Python
python 制作一个gui界面的翻译工具
May 14 Python
python结合API实现即时天气信息
Jan 19 #Python
Python+django实现文件下载
Jan 17 #Python
Python+django实现文件上传
Jan 17 #Python
初步剖析C语言编程中的结构体
Jan 16 #Python
举例讲解Python设计模式编程的代理模式与抽象工厂模式
Jan 16 #Python
python实现发送和获取手机短信验证码
Jan 15 #Python
详解python单例模式与metaclass
Jan 15 #Python
You might like
163的邮件用phpmailer发送(实例详解)
2013/06/24 PHP
Thinkphp3.2简单解决多文件上传只上传一张的问题
2017/09/26 PHP
PHP实现基本留言板功能原理与步骤详解
2020/03/26 PHP
为javascript添加String.Format方法
2020/08/11 Javascript
JS与框架页的操作代码
2010/01/17 Javascript
Javascript 键盘事件的组合使用实现代码
2012/05/04 Javascript
使用JavaScript动态设置样式实现代码及演示动画
2013/01/25 Javascript
JS格式化数字金额用逗号隔开保留两位小数
2013/10/18 Javascript
JS+CSS设置img在DIV中只显示Img垂直居中的部分
2013/10/24 Javascript
Nodejs中自定义事件实例
2014/06/20 NodeJs
JavaScript中的普通函数与构造函数比较
2015/04/07 Javascript
jQuery实现仿微软首页感应鼠标变化滑动窗口效果
2015/10/08 Javascript
简单介绍jsonp 使用小结
2016/01/27 Javascript
JavaScript学习总结之JS、AJAX应用
2016/01/29 Javascript
Bootstrap每天必学之日期控制
2016/03/07 Javascript
jQuery文件上传控件 Uploadify 详解
2016/06/20 Javascript
JavaScript变量声明var,let.const及区别浅析
2018/04/23 Javascript
关于vue路由缓存清除在main.js中的设置
2019/11/06 Javascript
jQuery 移除事件的方法
2020/06/20 jQuery
简单了解前端渐进式框架VUE
2020/07/20 Javascript
浅谈鸿蒙 JavaScript GUI 技术栈
2020/09/17 Javascript
Python实现字典的key和values的交换
2015/08/04 Python
基于python3实现socket文件传输和校验
2018/07/28 Python
浅谈django的render函数的参数问题
2018/10/16 Python
windows下python虚拟环境virtualenv安装和使用详解
2019/07/16 Python
使用OpenCV实现仿射变换—平移功能
2019/08/29 Python
python jenkins 打包构建代码的示例代码
2019/11/29 Python
pymysql 插入数据 转义处理方式
2020/03/02 Python
如何导出python安装的所有模块名称和版本号到文件中
2020/06/05 Python
百丽国际旗下购物网站:优购
2017/02/28 全球购物
KELLER SPORTS荷兰:在线订购最好的运动产品
2020/10/13 全球购物
通信工程专业女生个人求职信
2013/09/21 职场文书
2014民事授权委托书范本
2014/09/29 职场文书
党员批评与自我批评发言材料
2014/10/14 职场文书
人事专员岗位职责
2015/02/03 职场文书
Python中的datetime包与time包包和模块详情
2022/02/28 Python