def deco(obj):
obj.x = 1
obj.y = 2
return obj
@deco #相當於foo = deco(foo)
class foo:
pass
print(foo.__dict__)
@deco #相當於test = deco(test)
def test():
pass
print(test.__dict__)
輸出:
def typed(**kwargs):
def deco(obj):
for key,value in kwargs.items():
return deco
@typed(x=1,y=2) #先執行typed函式,返回值deco再和@組成@deco,相當於再執行foo=deco(foo)
class foo:
pass
@typed(name='alex')
def test():
pass
print(test.__dict__) #函式的屬性字典和例項化的屬性字典都是dict型別
輸出:
class typed: #描述符(型別限制)
def __init__(self,key,expected_type):
self.key = key
self.expected_type = expected_type
def __get__(self, instance, owner):
return instance.__dict__[self.key]
def __set__(self, instance, value):
if not isinstance(value,self.expected_type):
raise typeerror('%s傳入的型別不是%s'%(value,self.expected_type))
instance.__dict__[self.key] = value
def __delete__(self, instance):
print(instance.__dict__.pop(self.key))
def deco(**kwargs): #類的裝飾器(傳字典)
for key,value in kwargs.items():
setattr(obj,key,typed(key,value)) #給movie設定屬性,key是屬性名,值是描述符
return obj
@deco(title=str,rating=int,runtime=int,budget=int,gross=int)
class movie:
def __init__(self, title, rating, runtime, budget, gross):
self.title = title
self.rating = rating
self.runtime = runtime
self.budget = budget
self.gross = gross
d1 = movie('電影名稱',456,24,100000,200000)
print(movie.__dict__)
函式裝飾器 類裝飾器
一 函式裝飾函式 defwrapfun func definner a,b print function name func.name r func a,b return r return inner wrapfun defmyadd a,b return a b print myadd 2,3 二...
類的裝飾器
類的裝飾器 def deco func print return func deco test deco test def test print test函式執行 test deco foo deco foo class foo pass defdeco obj print obj obj.x 1o...
類的裝飾器
類的裝飾器 對不同的類使用裝飾器加上不同的類屬性 def typed kwargs defdeco obj for k,v in kwargs.items setattr obj,k,v return obj return deco typed x 1,y 2,z 3 1 typed x 1,y 2...