1. 程式人生 > >筆記-python-語法-property

筆記-python-語法-property

copy ict ext code let -a err etx python

筆記-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