利用描述符自定制property

 1 class property2:
 2     def __init__(self, func):
 3         print('执行property2')
 4         self.func = func
 5 
 6     def __get__(self, instance, owner):
 7         return self.func(instance)
 8 
 9 
10 class Room:
11     def __init__(self, name, width, length):
12         self.name = name
13         self.width = width
14         self.length = length
15 
16     @property2   # area = property2(area)  
17     def area(self):
18         return self.width * self.length
19 
20 
21 r1 = Room('cesuo', 100, 20)
22 print(r1.area)
23 
24 输出:
25 执行property2
26 2000

巧妙的利用描述符的__get__方法去调用类方法

posted @ 2020-03-16 12:19  竹石2020  阅读(130)  评论(0)    收藏  举报