类的装饰器

一、与函数的装饰器一样,类也可以被装饰

def deco(func):
    print('=============>')
    return func

@deco    #test = deco(test)
def test():
    print('test函数')

test()

在装饰器给类设置属性

def deco(obj):
    print('=============>')
    obj.x = 1
    obj.y = 2
    obj.z = 3
    return obj

@deco    #test = deco(test)
def test():
    print('test函数')

print(test.__dict__)

  

上述代码在装饰器函数中把属性写死了,如果不同的类需要设置不同的属性呢

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

@deco(x = 1,y = 2, z = 3)  #1.deco(x= 1,y= 2,z=3) --->wrapper 2.Foo = wrapper(Foo)
class Foo:
    pass

print(Foo.__dict__)

@deco(name= 'jinling')
class Bar:
    pass
print(Bar.name)
print(Bar.__dict__)

与前面描述符应用结合,类的装饰器的应用

class Typed:
    def __init__(self,key,excp_typed):
        self.key = key
        self.excp_typed = excp_typed
    def __get__(self, instance, owner):
        print('正在执行get方法')
        return instance.__dict__[self.key]
    def __set__(self, instance, value):
        print('正在执行set方法')
        if not isinstance(value,self.excp_typed):
            raise TypeError("你传入的参数类型不是",self.excp_typed)
        instance.__dict__[self.key] = value
    def __delete__(self, instance):
        print("正在执行delete方法")
        instance.__dict__.pop(self.key)

def deco(**kwargs):   #kwargs = {'name';str,'age':int}
    def wrapper(obj):  #obj = People
        for key, val in kwargs.items():  #(('name',str),('age',int))
            print("=====>")
            setattr(obj, key,Typed(key,val))  #People.name = Type('name',str)

        return obj
    return wrapper
@deco(name = str, age = int)   #@wrapper ==>People = wrapper(People)
class People:
    def __init__(self,name,age,salary):
        self.name = name
        self.age = age
        self.salary = salary

p1 = People('jinling',19,13000)
print(p1.__dict__)

  

  

 

posted @ 2019-10-13 13:10  绝世刘  阅读(174)  评论(0编辑  收藏  举报