失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python--装饰器 生成器 迭代器 元类

python--装饰器 生成器 迭代器 元类

时间:2024-04-01 10:32:48

相关推荐

python--装饰器 生成器 迭代器 元类

一、装饰器

def w1(func):def inner():func()return inner@w1def f1():print('1111111')

1.只要python解释器执行到装饰器,就会自动进行装饰,而不是等到调用的时候才进行装饰。

2.有参数的函数,装饰器定义方法

def w1(func):def inner(*args, **kwargs):func()return inner@w1def test1(a, b, c):print('1111')@w1def test2(a, b, c, d):print('2222')#这样不管调用时传几个参数,都可以灵活使用,无需修改装饰器的形参

3.对函数中有返回值,装饰器定义的方法

def w1(func):def inner():return func()return inner@w1 test1():return ('1111')res = test1()print(res)

4.通用装饰器

def w1(func):def inner(*args, **kwargs):return func()return inner@w1def test1():return ('1111')

5.数的装饰器

def func_arg(arg):def inner_func(func)def inner():func()return innerreturn func@func_art('1111')def class():print('1111')test()

带有参数的装饰器能够起到在运行时,有不同的功能

二、生成器

1.生成器的定义

# 第一种方式a = (x for x in range(10))# 第二种方式def func():a,b = 0,1for i in range(10):yield ba,b = b,a+b

生成器的定义

2.生成器赋值问题

def test():i = 0while i<5:temp = yield iprint(temp)i +=1t = test()t.__next__() #一种迭代方式next(t) #第二种迭代方式#在遍历过程中发现temp的值是None,即生成器未能给temp赋值,要解决这个问题可以用一下办法t.send('111') #在迭代的同时可以给temp赋值

生成器赋值问题

3.多任务

def test1():while True:print('11111')yield Nonedef test2():while True:print('22222')yield Nonet1 = test1()t2 = test2()while True:t1.__next__()t2.__next__()

多任务

三、迭代器

1.判断是否可以迭代

from collections import Iterableisinstance(要判断的变量,Iterable)

判断是否可以迭代

2.迭代器的定义

a = [11, 22, 33, 44]b = iter(a)

迭代器的定义

四、类装饰器

1.类装饰器的核心在于__call__方法见下例

class Test(object):def __init__(self, func):print('---初始化---')print('func name is %s'%func.__name__)self.__func = funcdef __call__(self):print('---装饰器中的功能---')self.__func()@Testdef test():print('---test---') #结果:---初始化--- func name is testtest() #结果:---装饰器中的功能--- ---test---

类装饰器

五、元类

1.用type创建类:type(类名, 由父类名称组成的元组(针对继承的情况,可以为空),包含属性的字典(名称和值)),定义方法可以先定义一个函数,然后把 函数的引用存在字典里

2.__metaclass__属性:在类中添加该属性 __metaclass__ = xxx(python2) 决定了该类是有什么创建的

python3中用法:class Test(object, metaclass=xxx):

如果觉得《python--装饰器 生成器 迭代器 元类》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。