我嘗試創建一個跟蹤裝飾器,以跟蹤哪個方法有調用。 讓我們先閱讀代碼。代碼是用Python編寫的2.7python裝飾代理不工作
class Decor(object):
def __init__(self,cls):
self.cls=cls
def __call__(self,*arg):
self.instance = self.cls(*arg)
return self
def __getattr__(self,name):
print "attribute name of instance of class {} = {}".format(self.cls.__name__,name)
return getattr(self.instance,name)
@Decor
class Foo(object):
attr1 = 10
def __init__(self,value):
self.value = value
def method1(self):
self.method2()
print self
print "value={}".format(self.value)
def method2(self):
print "hi"
f=Foo(10)
print f
f.method1()
輸出:
1. <__main__.Decor object at 0x02758B90>
2. attribute name of instance of class Foo = method1
3. hi
4. <__main__.Foo object at 0x02758C30>
5. value=10
我預計方法2將得到打印爲方法1。你能解釋爲什麼method2不能詳細打印嗎?
我不明白輸出line4。它顯示Foo對象而不是Decor對象。 f是一個Decor對象,爲什麼self是Foo對象?請解釋!
請給我一個解決這個問題的建議。謝謝