描述器,生成器,迭代器,序列器,装饰器
描述符协议:python描述符是一个“绑定行为”的对象属性,在描述符协议中,它可以通过方法重写属性的访问。这些方法有 _get_(), _set_(), 和_delete_()。如果这些方法中的任何一个被定义在一个对象中,这个对象就是一个描述符。
__dict__属性:字典类型,存放本对象的属性。
1.实例属性 obj.__dict__['attr_name']
2.类属性 type(obj).__dict__['attr_name']
3.如果2中返回了一个描述器,实例则用 type(obj).__dict__['x'].__get__(obj, type(obj))
4.如果是用class.x,类则用 type(class).__dict__['x'].__get__(None, type(class)
__get__函数参数
def __get__(self, instance, owner):
return self.name
__set__函数参数
def __set__(self, instance, value):
self.name = value
scrapy中用于返回json字符串
yield {
'text': quote.css('span.text::text').extract_first(),
'author': quote.css('small.author::text').extract_first(),
'tags': quote.css('div.tags a.tag::text').extract(),
}
scrapy中用于翻页
if next_page is not None:
yield scrapy.Request(next_page, callback=self.parse)
>>> a= iter([1,2,3,4,5])
>>> a
<list_iterator object at 0x0044ADF0>
>>> a.__next__()
1
>>> a.__next__()
2
>>> a.__next__()
3
序列器的叫法是我自己这么称呼的,因为已经有了迭代器,生成器,装饰器,描述器这么多器,而__getitem__函数和__len__ ,__setitem__ ,__delitem__这四个函数的作用也是让类具有python中类似list,tuple,dict等已经“序列化”的某一些特征,所以称呼这种机制为序列器也未尝不可
目标是为让binner可以有长度(len函数有效),可以按list方法取值(binner[i])
for i in range(0, len(binner)):
print(i, binner[i])
要求
装饰器是在已有的函数基础上再添加点东西,也就是说把已有的函数作为内置函数执行。
@classmethod 函数第一个参数不再是self,而是cls_obj
@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
@staticmethod 函数第一个参数不再是self,而是空。意思和其他语言的静态是一致的。
@staticmethod means: when this method is called, we don’t pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can’t access the instance of that class (this is useful when your method does not use the instance).
def myDecorator(func): # 函数作为参数
def wrapper(*args, **kwargs): # 作用是给函数传递参数
print("something before function run")
func(*args, **kwargs)
print("something after function run")
return wrapper #函数作为返回值
@myDecorator
def myAge():
print("my age is 25")
def myParamDecoratorMaker(arg1,arg2):
print('arg1='+arg1+ ' arg2='+arg2)
def myDecorator(func):
def wrapper(*args, **kwargs):
print("something before function run")
func(*args, **kwargs)
print("something after function run")
return wrapper
return myDecorator
@myParamDecoratorMaker('a','b')
def myAge():
print("my age is 25")