静态方法:
  只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性。

类方法:
  只能访问类变量,不能访问实例变量。

属性方法:
  把一个方法变成一个静态属性;隐藏实现细节。

静态方法

  通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法。其实不难理解,普通的方法,可以在实例化后直接调用,并且在方法里可以通过self. 调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法。

举例如下:

1、正常情况下:
class Dog(object):def __init__(self,name):self.name = namedef eat(self):print("%s is eating" % self.name)d = Dog("Dog1")
d.eat()
输出:
Dog1 is eating2、添加静态方法后:
class Dog(object):def __init__(self,name):self.name = name@staticmethod #实际上跟class类没有关系的一个函数糊,名义归类管。def eat(self):print("%s is eating" % self.name)d = Dog("Dog1")
d.eat()
输出报错信息:
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/mac/PycharmProjects/untitled2/51CTO/6day/静态方法1.py
Traceback (most recent call last):File "/Users/mac/PycharmProjects/untitled2/51CTO/6day/静态方法1.py", line 10, in <module>d.eat()
TypeError: eat() missing 1 required positional argument: 'self'

添加@staticmethod 静态方法后,上面的调用出现了错误,说是eat需要一个self参数,但调用时却没有传递,没错,当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。

让上面的代码可以正常工作有两种办法:
1. 调用时主动传递实例本身给eat方法,即d.eat(d)
2. 在eat方法中去掉self参数,但这也意味着,在eat中不能通过self.调用实例中的其它变量了

第一种方法:
class Dog(object):def __init__(self,name):self.name = name@staticmethoddef eat(self):print("%s is eating" % self.name)d = Dog("Dog1")
d.eat(d)  #调用时主动传递实例本身给eat方法,即d.eat(d)
输出:
Dog1 is eating第二种方法:
class Dog(object):def __init__(self,name):self.name = name@staticmethoddef eat(name): #更改这个位置,把self 去掉,就回到之前的函数传参调用的方法print("%s is eating" % name)d = Dog("123") #随意传个参数,def __init__(self,name):中需要用到。
d.eat("Dog1") #eat函数不会调用self.name,eat函数已独立出来,需要单独传参
输出:
Dog1 is eating

类方法

 类方法通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量

正常情况下:
class Dog(object):def __init__(self,name):self.name = namedef eat(self):print("%s is eating" % self.name)d = Dog("Dog1")
d.eat()
输出:
Dog1 is eating添加类方法后:
class Dog(object):def __init__(self,name):self.name = name@classmethoddef eat(self):print("%s is eating" % self.name)d = Dog("Dog1")
d.eat()
输出报错信息:
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/mac/PycharmProjects/untitled2/51CTO/6day/静态方法1.py
Traceback (most recent call last):File "/Users/mac/PycharmProjects/untitled2/51CTO/6day/静态方法1.py", line 11, in <module>d.eat()File "/Users/mac/PycharmProjects/untitled2/51CTO/6day/静态方法1.py", line 8, in eatprint("%s is eating" % self.name)
AttributeError: type object 'Dog' has no attribute 'name'

说Dog没有name属性,因为name是个实例变量,类方法是不能访问实例变量的。

让上面的代码可以正常工作的办法:可以定义一个类变量,也叫name。如下

class Dog(object):name = "Dog2"def __init__(self,name):self.name = name@classmethoddef eat(self):print("%s is eating" % self.name)d = Dog("Dog1")
d.eat()
输出:
Dog2 is eating   注意:添加类方法后,eat(self)调用了name = "Dog2"变量,类方法不能调用self.name 所以输出的为Dog2

属性方法

 属性方法的作用就是通过@property把一个方法变成一个静态属性

正常情况下:
class Dog(object):def __init__(self,name):self.name = namedef eat(self):print("%s is eating" % self.name)d = Dog("Dog1")
d.eat()
输出:
Dog1 is eating添加属性方法:
class Dog(object):def __init__(self,name):self.name = name@propertydef eat(self):print("%s is eating" % self.name)d = Dog("Dog1")
d.eat()
输出报错信息:
Dog1 is eating
Traceback (most recent call last):File "/Users/mac/PycharmProjects/untitled2/51CTO/6day/静态方法1.py", line 10, in <module>d.eat()
TypeError: 'NoneType' object is not callable

调用会出以下错误, 说NoneType is not callable, 因为eat此时已经变成一个静态属性了, 不是方法了, 想调用已经不需要加()号了,直接d.eat就可以了

class Dog(object):def __init__(self,name):self.name = name@property  #def eat  函数为静态属性def eat(self):print("%s is eating" % self.name)d = Dog("Dog1")
d.eat  #直接调用输出:
Dog1 is eating

属性方法的应用场景,举例:

想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态。

经历以下几步:
1. 连接航空公司API查询
2. 对查询结果进行解析
3. 返回结果给你的用户

  status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以。

class Flight(object):def __init__(self,name):self.name = namedef checking_status(self):print("checking flight %s status" % self.name)return 0@propertydef flight_status(self):status = self.checking_status()#定义静态变量,checking_status()根据return的返回值,进行判断if status == 0:print("flight got canceled...")elif status == 1:print("flight is arrived...")elif status == 2:print("flight has departured already...")else:print("cannot confirm the flight status...,please check later")f = Flight("CA988")
f.flight_status
输出:
checking flight CA988 status
flight got canceled...

flight_status既然已经是个属性,调用赋值的时候,就会报错:

class Flight(object):def __init__(self,name):self.name = namedef checking_status(self):print("checking flight %s status" % self.name)return 0@propertydef flight_status(self):status = self.checking_status()#定义静态变量,checking_status()根据return的返回值,进行判断if status == 0:print("flight got canceled...")elif status == 1:print("flight is arrived...")elif status == 2:print("flight has departured already...")else:print("cannot confirm the flight status...,please check later")f = Flight("CA988")
f.flight_status = 2  #调用赋值
输出摆错信息:
Traceback (most recent call last):File "/Users/mac/PycharmProjects/untitled2/51CTO/6day/静态方法1.py", line 24, in <module>f.flight_status = 2
AttributeError: can't set attribute

提示不能更改这个属性

如何可以调用的时候,正常赋值。需要添加@proerty.setter装饰器再装饰一下

class Flight(object):def __init__(self,name):self.name = namedef checking_status(self):print("checking flight %s status" % self.name)return 0@propertydef flight_status(self):status = self.checking_status()#定义静态变量,checking_status()根据return的返回值,进行判断if status == 0:print("flight got canceled...")elif status == 1:print("flight is arrived...")elif status == 2:print("flight has departured already...")else:print("cannot confirm the flight status...,please check later")@flight_status.setter #修改,相当于重新定义了一个函数def flight_status(self,status):status_dic = {0 : "canceled",1 : "arrived",2 : "departured"}print("\033[31;1mHas changed the flight status to \033[0m",status_dic.get(status) )@flight_status.deleter  #删除def flight_status(self):print("status got removed...")f = Flight("CA988")
f.flight_status = 2 #触发@flight_status.setter
del f.flight_status #触发@flight_status.deleter
输出:
Has changed the flight status to  departured
status got removed...

备注:@flight_status.deleter, 是允许可以将这个属性删除

转载于:https://www.cnblogs.com/chen170615/p/8523972.html

5、第六 - 面向对象高级语法-静态方法、类方法、属性方法相关推荐

  1. 类的实例方法静态方法类方法属性方法属性

    目录: 分类 实例方法 静态方法 类方法 属性方法 属性 分类: 按照调用方式可以分为3种,实例方法.静态方法.和类方法 实例方法 实例方法只能通过实例对象调用,不能通过类进行调用.实例方法再定义时候 ...

  2. 8、第六 -面向对象高级语法-异常处理

    异常错误:在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面. 1.异常基础 举例说明: python3 中的写法: try:pass except E ...

  3. Python类方法、实例方法、静态方法和属性方法详解

    静态方法(可调类变量.可被实例调用.可被类调用) 1.用 @staticmethod 装饰的不带 self 参数的方法叫做静态方法,类的静态方法可以没有参数,可以直接使用类名调用 2.静态方法名义上归 ...

  4. 向js中添加静态方法与属性方法

    前言 略 静态方法 if (!Date.diffDays) {Date.diffDays = function(s1, s2) {return Date.valueOf2(s1).diffDaysOf ...

  5. 六 面向对象高级属性

    一 isinstance(obj,cls)和issubclass(sub,super) 二 反射 三 __setattr__,__delattr__,__getattr__ 四 二次加工标准类型(包装 ...

  6. python3高级语法:__slots__属性、property装饰器、上下文管理协议、__new__方法

    #practice29:派生内置不可变类型并修改其实例化行为(以tuple为例) __new__() is intended mainly to allow subclasses of immutab ...

  7. python静态方法,类方法,属性方法,实例方法

    DAY 3. 静态方法,类方法,属性方法,实例方法 有四种方法,实例方法,类方法,静态方法,属性方法 实例方法 实例方法的第一个参数是self,他会指向类的实例化对象,只能被对象调用,如 class ...

  8. Cris 的 Scala 笔记整理(九):面向对象高级

    9. 面向对象高级 9.1 静态属性和静态方法 ① 回顾 Java 的静态概念 public static 返回值类型 方法名(参数列表) {方法体} Java 中静态方法并不是通过对象调用的,而是通 ...

  9. Python之路-面向对象继承和多态类属性和实例属性类方法和静态方法

    一.面向对象 编程方式 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可 面向对象:对函数进行分类和封装,让开发"更快更好更强-& ...

最新文章

  1. 服务器收集错误信息0不动,win10系统提示“我们只收集某些错误信息”的解决方案...
  2. pythonfor循环break_python 中 for 循环 if循环 break
  3. python四舍五入round_四舍五入就用round( )?Python四舍五入的正确打开方式!
  4. 用JQUERY为INPUT的TXT类型赋值及取值操作
  5. 设计模式(七)装饰模式
  6. 百度DuerOS负责人景鲲晋升副总裁,继续向李彦宏汇报
  7. 在Java下连接SQLite数据库
  8. sklearn库的学习
  9. n阶方阵的蛇形排列java_排列组合的模板算法
  10. 翻译:生产中的机器学习:为什么你应该关心数据和概念漂移
  11. Gephi教程———数据输入
  12. android学习资料整理-----高级篇
  13. 游戏开发中的脚本语言
  14. 假设有一个英文文本文件,编写一个程序读取其内容并将里面的大写字母变成小写字母,小写字母变成大写字母
  15. C语言———指针(1.3间接寻址运算符)
  16. openstack-mitaka(一) 架构简介
  17. 【无标题】口算小程序
  18. GSY 作为开发者,这四年走过的身影,感谢技术让你我相遇
  19. 1610C - Keshi Is Throwing a Party 题解
  20. make[2]: *** [/home/nnnn/calibration/devel/lib/libcalibrationtoolkit.so] Error 1

热门文章

  1. 2021年全球及中国奢侈品行业发展现状及未来发展趋势分析:中国占全球个人奢侈品市场份额的20%[图]
  2. chrome浏览器如何将网页保存为图片
  3. Python使用QQ邮箱发送多收件人email
  4. 使用JavaScript解决网页图片拉伸问题
  5. 通过浏览器直接打开android应用程序,通过浏览器直接打开Android App 应用程序
  6. flask系列---模板的继承及Bootstrap实现导航条(四)
  7. 慎用安卓USB调试模式 谨防陷入安全危机
  8. 他山之石——VBA自定义函数
  9. 基于C++OpenGL实现的五角形绘制
  10. 平面设计实验二 相册的制作与图层