举例讲解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实现包含min函数的栈
Apr 29 Python
Python实现快速傅里叶变换的方法(FFT)
Jul 21 Python
Python3 利用requests 库进行post携带账号密码请求数据的方法
Oct 26 Python
对Python捕获控制台输出流的方法详解
Jan 07 Python
Python button选取本地图片并显示的实例
Jun 13 Python
python实现的接收邮件功能示例【基于网易POP3服务器】
Sep 11 Python
简单了解python元组tuple相关原理
Dec 02 Python
解决pycharm导入本地py文件时,模块下方出现红色波浪线的问题
Jun 01 Python
Python 测试框架unittest和pytest的优劣
Sep 26 Python
Python使用windows设置定时执行脚本
Nov 12 Python
一文带你了解Python 四种常见基础爬虫方法介绍
Dec 04 Python
AI:如何训练机器学习的模型
Apr 16 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
YiiFramework入门知识点总结(图文教程)
2015/12/28 PHP
深入分析PHP优化及注意事项
2016/07/04 PHP
laravel 实现登陆后返回登陆前的页面方法
2019/10/03 PHP
最常用的12种设计模式小结
2011/08/09 Javascript
一个页面放2段图片滚动代码出现冲突的问题如何解决
2012/12/21 Javascript
JQuery的read函数与js的onload不同方式实现
2013/03/18 Javascript
javascript使用isNaN()函数判断变量是否为数字
2013/09/21 Javascript
检查输入的是否是数字使用keyCode配合onkeypress事件
2014/01/23 Javascript
JS解析XML实例分析
2015/01/30 Javascript
jQuery实现tab标签自动切换的方法
2015/02/28 Javascript
JavaScript高级教程5.6之基本包装类型(详细)
2015/11/23 Javascript
JavaScript深度复制(deep clone)的实现方法
2016/02/19 Javascript
jQuery插件扩展extend的简单实现原理
2016/06/24 Javascript
详解ES6之async+await 同步/异步方案
2017/09/19 Javascript
JS实现点击链接切换显示隐藏内容的方法
2017/10/19 Javascript
详解js的作用域、预解析机制
2018/02/05 Javascript
jQuery 改变P标签文本值方法
2018/02/24 jQuery
详解封装基础的angular4的request请求方法
2018/06/05 Javascript
对angularJs中自定义指令replace的属性详解
2018/10/09 Javascript
js的继承方法小结(prototype、call、apply)(推荐)
2019/04/17 Javascript
Vue form表单动态添加组件实战案例
2019/09/02 Javascript
[49:59]KG vs Mineski 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/16 DOTA
Python实现Const详解
2015/01/27 Python
python Selenium爬取内容并存储至MySQL数据库的实现代码
2017/03/16 Python
Python使用openpyxl读写excel文件的方法
2017/06/30 Python
Python3一行代码实现图片文字识别的示例
2018/01/15 Python
Caffe均值文件mean.binaryproto转mean.npy的方法
2018/07/09 Python
python怎么调用自己的函数
2020/07/01 Python
css3实现wifi信号逐渐增强效果实例
2017/08/09 HTML / CSS
师德模范事迹材料
2014/06/03 职场文书
商业项目策划方案
2014/06/05 职场文书
出生证明范本
2015/06/15 职场文书
只需要12页,掌握撰写一流商业计划书的技巧
2019/05/07 职场文书
JPA如何使用entityManager执行SQL并指定返回类型
2021/06/15 Java/Android
深入理解CSS 中 transform matrix矩阵变换问题
2021/08/30 HTML / CSS
漫画「请问您今天要来点兔子吗?」最新杂志彩页公开
2022/03/24 日漫