property 用法

本文介绍了Python中如何使用property函数来定义类属性,并通过@property装饰器简化这一过程。展示了如何实现只读属性及带有设置和删除操作的属性。
 1 _DEFAULT_CONFIG = {
 2     'name':None
 3 }
 4 
 5 class TestProperty(object):
 6     def __init__(self, config):
 7         self._config = config or {}
 8 
 9     def __GetName(self):
10         return self._config['name']
11 
12     def __SetName(self, name):
13         self._config['name'] = name
14     
15     def __DeleteName(self):
16         del self._config['name']
17 
18     name = property(__GetName, __SetName, __DeleteName)
19 
20 if __name__ == '__main__':
21     tp = TestProperty(_DEFAULT_CONFIG)
22     tp.name = '250'
23     print tp.name
24     del tp.name
25     print tp.name #抛错,已经没有name属性

property 函数原型property([fget[, fset[, fdel[, doc]]]])

fget,fset,fdel 分别为取值,设值,删除值

函数自动为对象生成name属性,前提是类定义时不能有属性name,否则property函数会自动覆盖将原name属性覆盖。

 

@property

创建只读属性可以用@property

 1 class Property(object):
 2     def __init__(self):
 3         self.name = 'leon liang'
 4 
 5     @property
 6     def username(self):
 7         return self.name
 8 
 9     @property
10     def password(self, bb): #这是错误的,调用时会出错
11         return bb + 1
12 
13 if __name__ == '__main__':
14     obj = Property()
15     print obj.username
16     print obj.password(1) #调用出错

转载于:https://www.cnblogs.com/bjdxy/archive/2012/11/14/2769415.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值