首页 > 编程语言 > 详细

python中property简单实用与实现

时间:2019-06-06 21:45:02      阅读:112      评论:0      收藏:0      [点我收藏+]

property简单使用

技术分享图片
 1 class P:
 2     """
 3         property简单使用
 4     """
 5     def __init__(self,name):
 6         self._name = name
 7 
 8     @property
 9     def name(self):
10         return self._name
11 
12     @name.setter
13     def name(self,val):
14         self._name = val
15 
16     @name.deleter
17     def name(self):
18         del self._name
19 
20 
21 p = P("zhangsan")
22 print(p.name)
23 print(p.__dict__)
24 p.name = "wangsi"
25 print(p.name)
26 print(p.__dict__)
View Code

结果:

技术分享图片
1 zhangsan
2 {_name: zhangsan}
3 wangsi
4 {_name: wangsi}
View Code

 

property简单实现

技术分享图片
 1 class Property:
 2 
 3     def __init__(self,fget=None,fset=None,fdel=None):
 4         self.fget = fget
 5         self.fset = fset
 6         self.fdel = fdel
 7         pass
 8 
 9     def __set__(self, instance, value):
10         self.fset(instance,value)
11         return self
12 
13     def __get__(self, instance, owner):
14         if not instance:
15             return self
16         return self.fget(instance)
17 
18     def __delete__(self, instance):
19         self.fdel(instance)
20         return self
21 
22     def setter(self,fn):
23         #保留设置函数的副本
24         self.fset = fn
25         return self
26 
27     def deleter(self,fn):
28         # 保留删除函数的副本
29         self.fdel = fn
30         return self
31 
32 
33 class Person:
34 
35     # d = Property()
36     def __init__(self,data):
37         self._data = data
38 
39     @Property   #等价式  data=Propery(data)
40     def data(self):
41         return self._data
42 
43     @data.setter   #等价式  data=data.setter(data)
44     def data(self,val):
45         self._data = val
46 
47     @data.deleter  #等价式  data=data.deleter(data)
48     def data(self):
49         del self._data
50 
51 
52 p = Person(19)
53 p.data = 123
54 print(Person.__dict__)
55 print(p.__dict__)
56 del p.data
57 print(Person.__dict__)
58 print(p.__dict__)
View Code

结果:

技术分享图片
1 {__init__: <function Person.__init__ at 0x0000015F3F0F0598>, __dict__: <attribute __dict__ of Person objects>, data: <__main__.Property object at 0x0000015F3F0FE240>, __weakref__: <attribute __weakref__ of Person objects>, __module__: __main__, __doc__: None}
2 {_data: 123}
3 {__init__: <function Person.__init__ at 0x0000015F3F0F0598>, __dict__: <attribute __dict__ of Person objects>, data: <__main__.Property object at 0x0000015F3F0FE240>, __weakref__: <attribute __weakref__ of Person objects>, __module__: __main__, __doc__: None}
4 {}
View Code

 

注意:property 依赖装饰器和数据描述器实现

  数据描述器:需要实现__set__()方法和__get__()方法

  非数据描述器:需实现__get__()方法

python中property简单实用与实现

原文:https://www.cnblogs.com/lanxiansen/p/10986932.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!