笔记-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并不是必需的。

怎么实现的就不讨论了,总而言之它可以简化实例属性操作,简化代码。

05-22 21:25