练习内容:
模拟property描述器。
1.实现一个类,模拟property数据描述器
1 class Property: 2 def __init__(self, get_attrib_func): 3 self.get_attrib_func = get_attrib_func 4 self.set_attrib_func = None 5 6 def __set__(self, instance, value): 7 if not self.set_attrib_func: 8 raise AttributeError("can't set attribute") 9 self.set_attrib_func(instance, value) 10 11 def __get__(self, instance, owner): 12 return self.get_attrib_func(instance) 13 14 def setter(self, set_attrib_func): 15 self.set_attrib_func = set_attrib_func 16 return self
2.简单的测试代码
1 class Person: 2 def __init__(self, name, age): 3 self._name = name 4 self._age = age 5 6 @Property # name = Property(name) 7 def name(self): 8 return self._name 9 10 @name.setter # name = Property(name).setter(name) 11 def name(self, name): 12 self._name = name 13 14 @Property # age = Property(age) 15 def age(self): 16 return self._age 17 18 # @age.setter # age = Property(age).setter(age) 19 # def age(self, age): 20 # self._age = age 21 22 def __str__(self): 23 return "<Person:{}:{}>".format(self._name, self._age) 24 25 __repr__ = __str__ 26 27 if __name__ == "__main__": 28 p = Person("tom", 19) 29 print(type(p.name), type(p.age)) 30 p.name = "jerry" # OK 31 print("~" * 100) 32 p.age = 200 # AttributeError: can't set attribute