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 的功能就是类或类的实例化对象调用类的方法时,只需要用 类.方法名对象名.方法名 不需要加括号就可直接调用。

相关文章:

  • 2022-02-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-17
  • 2022-12-23
  • 2021-06-08
猜你喜欢
  • 2022-01-07
  • 2021-07-23
  • 2021-09-04
  • 2021-12-13
  • 2021-09-03
  • 2021-08-28
  • 2021-09-17
相关资源
相似解决方案