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

一、装饰器

def w1(func):
    def inner():
        func()
    return inner

@w1
def f1():
    print('1111111')

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

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

def w1(func):
    def inner(*args, **kwargs):
        func()
    return inner

@w1
def test1(a, b, c):
    print('1111')

@w1
def 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

@w1
def test1():
    return ('1111')

5.数的装饰器

def func_arg(arg):
    def inner_func(func)
        def inner():
            func()
        return inner
    return func

@func_art('1111')
def class():
    print('1111')

test()

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

二、生成器

  1.生成器的定义

# 第一种方式
a = (x for x in range(10))

# 第二种方式
def func():
    a,b = 0,1
    for i in range(10):
        yield b
        a,b = b,a+b
生成器的定义

  2.生成器赋值问题

def test():
    i = 0
    while i<5:
        temp = yield i
        print(temp)
        i +=1

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

  3.多任务

def test1():
    while True:
        print('11111')
        yield None

def test2():
    while True:
        print('22222')
        yield None

t1 = test1()
t2 = test2()

while True:
    t1.__next__()
    t2.__next__()
多任务

三、迭代器

  1.判断是否可以迭代

from collections import Iterable

isinstance(要判断的变量,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 = func
    def __call__(self):
        print('---装饰器中的功能---')
        self.__func()

@Test
def test():
    print('---test---')    #结果:---初始化--- func name is test

test()    #结果:---装饰器中的功能---  ---test---
类装饰器

五、元类

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

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

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

原文地址:https://www.cnblogs.com/peilanluo/p/8284255.html