- 方法1
class C1:
def __init__(self):
self._x = None
def getx(self):
print('getx')
return self._x
def setx(self, value):
print('setx')
self._x = value
def delx(self):
print('delx')
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
c = C1()
c.x =1
print(c.x)
c.y =2
print(c.y)
- 方法2
class C2(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
print("getter of x called")
return self._x # 注意这里是return
@x.setter
def x(self, value):
print("setter of x called")
self._x = value
@x.deleter
def x(self):
print("deleter of x called")
del self._x
c2 = C2()
c2.x=1
print(c2.x)
c2.y=2
print(c2.y)