实现类property装饰器,类名称为Property
class Property:
def __init__(self, fget, fset=None):
self.fget = fget
self.fset = fset
def __get__(self, instance, owner):
if instance:
return self.fget(instance)
raise AttributeError()
def __set__(self, instance, value):
if self.fset is None:
raise AttributeError("can't set attribute")
self.fset(instance, value)
def setter(self, fn):
self.fset = fn
return self
class A:
def __init__(self, data):
self._data = data
@Property
def data(self):
return self._data
@data.setter
def data(self, value):
self._data = value
a = A(10)
print(a.data)
a.data = 1000
print(a.data)
10
1000