高階玩法之類的裝飾器的應用

派森马發表於2024-08-06

一、類的裝飾器:

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

三、類的裝飾器結合描述符的應用

def deco(**kwargs):
    def warpper(obj):
        for key,value in kwargs.items(): #((name,str),(age,int),(salary,float))
            setattr(obj,key,Typed(key,value))
        return obj
    return warpper

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

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

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

上面的程式碼看著很牛逼,實際上也很牛逼。能看懂就行,不必非要掌握,一般用不到。

相關文章