>>> from env_helper import info; info()
页面更新时间: 2023-06-30 18:56:11
运行环境:
Linux发行版本: Debian GNU/Linux 12 (bookworm)
操作系统内核: Linux-6.1.0-9-amd64-x86_64-with-glibc2.36
Python版本: 3.11.2
13.9. 无聊的@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)
alex
看上去的确好用,但其实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)
alex
结果当然是:alex。