Python的高级特性10:无聊的@property
@property装饰器其实有点无聊,单独拿出来作为一个知识点其实没必要,尽管它可以将方法变成属性,让get和set方法更好用,但是,它破坏了python的简洁(不是代码的简洁而是指语法上)。
下面来说明为什么我会这么说。
首先,看一个使用property。
class Student(object): @property def testname(self): return self.name @testname.setter def testname(self,name): self.name = name s = Student() s.testname = "alex" print(s.testname)
结果是:
/System/Library/Frameworks/Python.framework/Versions/3.4/bin/python3 /Users/lsf/PycharmProjects/py3Project/test3.py
alex
Process finished with exit code 0
看上去的确好用,但其实python内置的__getattr__和__setattr__就是将方法变为属性功能的。
class Stu(object): def __init__(self): pass def __setattr__(self,name,value): self.__dict__[name] = value def __getattr__(self): return self.name s = Stu() s.name = 'alex' print(s.name)
结果当然是:
/System/Library/Frameworks/Python.framework/Versions/3.4/bin/python3 /Users/lsf/PycharmProjects/py3Project/test3.py
alex
Process finished with exit code 0