python中最基本的,也許是不知道的

python中最基本的,也許是不知道的

一 引子

在看scrapy源碼中,在Crawler類中就有:

@property

def spiders(self):

if not hasattr(self, '_spiders'):

warnings.warn("Crawler.spiders is deprecated, use "

"CrawlerRunner.spider_loader or instantiate "

"scrapy.spiderloader.SpiderLoader with your "

"settings.",

category=ScrapyDeprecationWarning, stacklevel=2)

self._spiders = _get_spider_loader(self.settings.frozencopy())

return self._spiders

類中使用@property,顧名思義,property應該是表示的屬性。而具體怎麼使用,還真不明白,於是翻查資料……

二 @property介紹

python官網對於property解釋如下:

class property(fget=None, fset=None, fdel=None, doc=None)¶

Return a property attribute.

fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute.

@propety有三種形式,fget, fset, fdel。 從名字上可以理解到是修飾一個函數作為讀,寫,刪的作用。

三. @property使用方法

如果在java語言中些一個類的屬性或在沒有學習property之前寫一個屬性時,形式應該如下:

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.")

當使用property形式寫的話,就變成了這個樣子:

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

if __name__ == '__main__':

c = C()

# 執行x.setter

c.x = 'c'

# 執行property

print(c.x)

# 執行x.deleter

del c.x

print(c.x)

返回結果

c

Traceback (most recent call last):

File "D:/code/python/lab/labs/pythonstudy/property.py", line 34, in

print(c.x)

File "D:/code/python/lab/labs/pythonstudy/property.py", line 18, in x

return self._x

AttributeError: 'C' object has no attribute '_x'

四 總結

通過以上例子可以知道property使用方法如下:

1.@property是作為一個裝飾器使用的

2.@property相當於getx, @x.seteer相當於 setx @xdeleter相當於delx。

3. 一定要保證和property對應的寫,刪屬性其屬性名相同。

4. 對應deleter調用使用del命令


分享到:


相關文章: