经常在python程序里看到,@property 这个东西,到底用来做什么的。主要就是用来把方法变成属性调用,也就是是更pythonic。
将一个方法变为只读对象
class Test(object):
def __init__(self, para):
self.para = para
@property
def only_para(self):
return 'para:%s'% self.para
cc = Test("hello, world!")
print cc.only_para
cc.only_para = 'try' # 这一步会报错
Traceback (most recent call last):
File "proper.py", line 21, in <module>
cc.only_para = 'try'
AttributeError: can't set attribute
当加了property这个装饰器后,only_para变成了一个只读的属性gettattr,先在再给他加一个setattr属性
class Test(object):
def __init__(self, para):
self.para = para
@property
def normal_para(self):
return 'para:%s'% self.para
@normal_para.setter
def normal_para(self, value):
if isinstance(value, str):
self.para = "string"
elif isinstance(value, int):
self.para = 10
cc = Test("hello, world!")
print cc.normal_para
cc.normal_para = 100
print cc.normal_para
# output
para:hello, world!
para:10
可以看到属性设置成功,normal_para参数已经改变。
总结一下就是,property这个装饰器就如同名字一样,讲过方法转为属性。在设计代码时灵活运用这个装饰器可以让代码更pythonic