笔记-python-语法-property
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了笔记-python-语法-property,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2674字,纯文字阅读大概需要4分钟。
内容图文
![笔记-python-语法-property](/upload/InfoBanner/zyjiaocheng/850/dfb2afa074134727ad2839747928ea1a.jpg)
笔记-python-语法-property
1. property
看到@property,不明白什么意思,查找文档了解一下。
1.1. property类
proerty是python自带的类,在
>>> property
<class 'property'>
>>> dir(property)
['__class__', '__delattr__', '__delete__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__isabstractmethod__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__set__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'deleter', 'fdel', 'fget', 'fset', 'getter', 'setter']
>>> property.__class__
<class 'type'>
官方文档:
class property(fget=None, fset=None, fdel=None, doc=None)
Return a property attribute.
fget是一个获取属性值的函数,fset是设定值的函数,fdel是删除值的函数。doc创建属性的说明文档。
案例:
class C:
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
运行结果如下:
>>> C.x
<property object at 0x000000BC05B078B8>
>>> dir(C)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'delx', 'getx', 'setx', 'x']
解释:上面的代码给类C添加了一个属性x,而x是一个property对象,这样做的结果是可以像下面这样操作self._x
>>> a = C()
赋值
>>> a.x = 6
>>> a._x #6
删除
>>> del(a.x)
>>> a.x
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
a.x
File "E:\python\person_code\interview questions\built-in.py", line 47, in getx
return self._x
AttributeError: 'C' object has no attribute '_x'
>>> a._x
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
a._x
AttributeError: 'C' object has no attribute '_x'
最终的结果就是简化了实例对象属性的操作代码。
再看下面的代码:
A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function.
This is best explained with an example:
class C:
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
这里使用的装饰符实现,功能与上例没什么区别,但代码更简洁。
注意seter和deleter并不是必需的。
怎么实现的就不讨论了,总而言之它可以简化实例属性操作,简化代码。
内容总结
以上是互联网集市为您收集整理的笔记-python-语法-property全部内容,希望文章能够帮你解决笔记-python-语法-property所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。