[英]Working around decorator and getattr
我無法解決此問題,我有以下課程:
class test:
@auth
def method1(self, x):
return x
@auth
def method2(self, x, y):
return x+y
def method3(self, z):
return z
我在兩種方法中都應用了裝飾器,方法如下:
class auth:
def __init__(self, f):
self.f = f
def __call__(self, *args, **kwargs):
self.f(*args, **kwargs)
到目前為止沒有問題,但是我需要(NEED)使用以下代碼:
def run():
klass = globals()["test"]()
method1 = getattr(klass, "method1")
print(method1.__code__.co_varnames)
# should print (self, x)
method2 = getattr(klass, "method2")
print(method2.__code__.co_varnames)
# should print (self, x, y)
method3 = getattr(klass, "method3")
print(method3.__code__.co_varnames)
# i get (self, z) < without decorator
但我現在得到:
AttributeError: 'auth' object has no attribute '__code__'
如果我們認為方法“ method1 and method2”的簽名現在是“ auth”,那是有道理的。
因此,如何獲得帶有或不帶有修飾符的參數。 我開始閱讀有關“檢查”的信息,但是有許多關於運行緩慢的報告。
“原始”方法存儲在auth
對象的f
屬性中。 代替method1.__code__.co_varnames
使用method1.f.__code__.co_varnames
注釋僅包含一個對象,而不是其自身,它是auth
類而不是function
的對象。 要訪問函數本身,可以編寫方法methodN.f.__code__.co_varnames
或將函數的__dict__
對象的副本分配給__init__
自身的auth對象。
class auth:
def __init__(self, f):
self.__dict__.update(f.__dict__)
# now the initialisations
self.f = f
def __call__(self, *args, **kwargs):
self.f(*args, **kwargs)
編輯:更新字典后,您應該初始化成員/超級調用,因為更新可能會覆蓋f
,例如。 您定義另一個裝飾器類,並且它還具有成員f
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.