码迷,mamicode.com
首页 > 其他好文 > 详细

利用描述符自定制property

时间:2020-03-16 12:29:49      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:col   code   idt   int   描述符   输出   style   def   Owner   

 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__方法去调用类方法

利用描述符自定制property

标签:col   code   idt   int   描述符   输出   style   def   Owner   

原文地址:https://www.cnblogs.com/ch2020/p/12503018.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!