高端玩法之类的装饰器的应用

一、类的装饰器:

def deco(obj):
    obj.x=2
    obj.y=3
    return obj
@deco
class Foo:
    pass

print(Foo.__dict__)

二、类的装饰器增强版

def deco(**kwargs):
    def warpper(obj):
       for key,value in kwargs.items():
           setattr(obj,key,value)
       return obj
    return warpper

@deco(x=1,y=2)
class Foo:
    pass

@deco(name='jack')
class Bar:
    pass
print(Foo.__dict__)
print(Bar.__dict__)
输出结果:
D:\python\python.exe D:/software/project/描述符.py
{'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'x': 1, 'y': 2}
{'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Bar' objects>, '__weakref__': <attribute '__weakref__' of 'Bar' objects>, '__doc__': None, 'name': 'jack'}

Process finished with exit code 0

三、类的装饰器结合描述符的应用

class Typed:
    def __init__(self,key,mytype):
        self.key=key
        self.mytype=mytype
    def __get__(self, instance, owner):
        return instance.__dict[self.key]
    def __set__(self, instance, value):
        if not isinstance(value,self.mytype):
            raise TypeError('你输入的%s不是%s类型' %(self.key,self.mytype))
        instance.__dict__[self.key]=value
    def __delete__(self, instance):
        return instance.__dict.pop(self.key)

def deco(**kwargs):
    def warpper(obj):
        for key,value in kwargs.items():
            setattr(obj,key,Typed(key,value)) #name=Typed('name',str)
        return obj
    return warpper

@deco(name=str,age=int,salary=float) #@warpper people=warpper(people)
class People:
    # name=Typed('name',str)
    # age=Typed('age',int)
    # salary=Typed('salary',float)
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.salary=salary

p=People('jack',20,30.6)
p.age=30
print(p.__dict__)

记住一个重要理念,在python中一切皆对象,函数是对象,变量是对象,类也是对象。前面@deco(name=str,age=int,salary=float) 就是在执行deco类,执行类就是实例化一个对象,因为return的是warpper,就是@deco(name=str,age=int,salary=float) 等价于@warpper,而@warpper等价于People=warpper(People),还记得装饰器吧,这样就可以在装饰器def deco中去操作People类的属性了,因为最终return的就是People。
上面的代码看着很牛逼,实际上也很牛逼。能看懂就行,不必非要掌握,一般用不到。

posted @   疯狂Python  阅读(5)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示