使用场景一
class Test:
def __init__(self):
self._x = None
def getx(self):
print(f'{__class__}-{sys._getframe().f_code.co_name}开始执行')
return self._x
def setx(self, value):
print(f'{__class__}-{sys._getframe().f_code.co_name}开始执行')
self._x = value
print(f'{__class__}-{sys._getframe().f_code.co_name}结束执行')
def delx(self):
print(f'{__class__}-{sys._getframe().f_code.co_name}开始执行')
del self._x
x = property(getx,setx,delx,"x property")
if __name__ == '__main__':
t1 = Test()
print(t1.x)
t1.x = 11
print(t1.x)
del t1.x
print(t1.x)
"""
<class '__main__.Test'>-getx开始执行
None
<class '__main__.Test'>-setx开始执行
<class '__main__.Test'>-setx结束执行
<class '__main__.Test'>-getx开始执行
11
<class '__main__.Test'>-delx开始执行
<class '__main__.Test'>-getx开始执行
AttributeError: 'Test' object has no attribute '_x'
"""
使用场景二
class Test2:
def __init__(self):
self._x = None
@property
def x(self):
return self._x
@x.setter
def setx(self, value):
self._x = value
@x.deleter
def delx(self):
del self._x
if __name__ == '__main__':
t2 = Test2()
print(t2.x)
t2.setx = 12
print(t2.x)
del t2.delx
print(t2.x)
"""
None
12
AttributeError: 'Test2' object has no attribute '_x'
"""
|