@property:就像访问属性一样和普通访问少了一个(),将函数名作为一个返回值 被装饰的类方法不可回调
@staticmethod: 可以直接通过类名.函数名直接调用被装饰的方法
@classmethod: 可以直接通过类名.函数名直接调用被装饰的方法
class Myclass():
a=100#类属性
def __init__(self,height,width):
self.height=height#实例属性
self.width=width
@property #属性装饰器:将函数名作为一个返回值 被装饰的类方法不可回调
def get_area(self):
#因为外部可以直接通过实例对象.函数名调用来获得结果 所以必须得有返回值
#通过类名.函数名调用只能得到该方法的地址 等于下面的cls.get_area
return self.height*self.width
@classmethod #类方法装饰器:可以通过类名.函数名直接调用被装饰的方法
def info(cls):
print('you can use class attribution and class method!')
print(cls.a,cls.get_area)#可以通过cls调用类属性和类方法
@staticmethod#静态装饰器:可以直接通过类名.函数名直接调用被装饰的方法
def help():
print('there is no cls and self!')
a=Myclass(20,50)
print('-----------实例化对象.函数名调用----------------')
print(a.get_area)
print('-----------类名.函数名调用----------------')
print(Myclass.get_area)
print('---------实例化对象.函数调用----------')
a.info()
a.help()
print('---------类名.函数直接调用----------')
Myclass.info()
Myclass.help()
# 输出:
# >>-----------实例化对象.函数名调用----------------
# 1000
# >>---------实例化对象.函数调用----------
# >>you can use class attribution and class method!
# >>100 <property object at 0x0000025D9322D958>
# >>there is no cls and self!
# >>---------类名.函数直接调用----------
# >>you can use class attribution and class method!
# >>100 <property object at 0x0000025D9322D958>
# >>there is no cls and self!
@staticmethod和@classmethod的区别:
@staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。