一、类的装饰器:
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__)
上面的代码看着很牛逼,实际上也很牛逼。能看懂就行,不必非要掌握,一般用不到。
标签:__,obj,高端,self,玩法,dict,key,装饰,def From: https://www.cnblogs.com/kkbest/p/18342200