使用描述符实现property功能

 1 # Author : Kelvin
 2 # Date : 2019/1/25 14:46
 3 class Decproperty:
 4     def __init__(self, func):
 5         self.func = func
 6 
 7     def __get__(self, instance, owner):
 8         print("get")
 9         if instance is None:
10             return self
11         res = self.func(instance)
12         setattr(instance, self.func.__name__, res)
13         return res
14 
15 
16 class People:
17     def __init__(self, name, age):
18         self.name = name
19         self.age = age
20 
21     @Decproperty
22     def Age(self):
23         return "%s的年龄是%d" % (self.name, self.age)
24 
25 
26 p = People("kelvin", 20)
27 print(p.Age)
28 print(p.__dict__)
29 print(p.Age)
30 print(p.Age)

@property 的功能就是类或类的实例化对象调用类的方法时,只需要用 类.方法名对象名.方法名 不需要加括号就可直接调用。

原文地址:https://www.cnblogs.com/sun-10387834/p/10319693.html