1.静态属性property
在类的函数属性前加@property可以让该函数以数据属性的方式调用.
注意:1. 静态属性不可传参数,(只有self)
2.类的实例默认无法修改静态属性
3.如果想对实例修改,调用静态属性做限制,可以用setter, getter, deleter,等装饰器.
示例1:property使用
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
@property
def cal1(self):
return self.a + self.b
@cal1.setter # 利用此方法设置静态属性
def cal1(self, value):
print('hahaha', self, value)
self.__dict__['cal1'] = value # 直接操作字典,避免无限递归
@cal1.getter # 调用属性时触发,触发条件只与实例有关
def cal1(self):
print('get is running')
return self.a + self.b
@cal1.deleter
def cal1(self): # 删除静态属性时触发
print('deleter is running')
self.__dict__.pop('cal1')
t = Test('love', 'you')
print(t.cal1)
print(Test.cal1)
t.cal1 = 'sa' # 而实例不可设置静态属性,除非有setter
#Test.cal1 = 'happy' # 类可以设置静态属性
print(t.__dict__)
del t.cal1
print(t.__dict__)
#result
get is running
loveyou
<property object at 0x000001AD05B61B88>
hahaha <__main__.Test object at 0x000001AD05B6E0F0> sa
{'a': 'love', 'b': 'you', 'cal1': 'sa'}
deleter is running
{'a': 'love', 'b': 'you'}
示例2:静态属性设置的另一种格式(完全等价于示例1)
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def setcal1(self, value):
print('hahaha', self, value)
self.__dict__['cal1'] = value # 直接操作字典,避免无限递归
def getcal1(self):
print('get is running')
return self.a + self.b
def delcal1(self): # 删除静态属性时触发
print('deleter is running')
self.__dict__.pop('cal1')
cal1 = property(getcal1, setcal1, delcal1)
t = Test('love', 'you')
print(t.cal1)
print(Test.cal1)
t.cal1 = 'sa'
print(t.__dict__)
del t.cal1
print(t.__dict__)
#result
get is running
loveyou
<property object at 0x000002109EF61C28>
hahaha <__main__.Test object at 0x000002109EF6E128> sa
{'a': 'love', 'b': 'you', 'cal1': 'sa'}
deleter is running
{'a': 'love', 'b': 'you'}