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命令


分享到:


相關文章: