注意使用父類的裝飾:Python的裝飾:如何在子類
對其他問題接受的答案顯示瞭如何使用父decorater。
該問題的接受答案顯示將裝飾器移動到模塊範圍。
編輯:使用前面的例子是一個壞主意。希望這是更清晰:
class A:
def deco(func):
print repr(func)
def wrapper(self, *args):
val = func(*args)
self.do_something()
return val
return wrapper
def do_something(self):
# Do something
print 'A: Doing something generic for decoration'
@deco
def do_some_A_thing (self):
# Do something
print 'A: Doing something generic'
class B (A):
@deco
def do_some_B_thing(self):
# Do something
print "B: Doing something specific"
a = A()
b = B()
a.do_some_A_thing()
b.do_some_B_thing()
#Expected Output:
#A: Doing something generic
#A: Doing something generic for decoration
#B: Doing something specific
#A: Doing something generic for decoration
此代碼生成一個NameError:名字「裝飾」不是內部B. 定義的裝飾需要是一流的範圍內,因爲我需要訪問存儲的狀態。
三編輯:在斯文的建議,我嘗試這樣做:
class A:
def deco(func):
def wrapper(self, *args):
val = func(*args)
self.do_something(*args)
return val
return wrapper
def do_something(self):
# Do something
print 'A: Doing something generic for decoration'
@deco
def do_some_A_thing (self):
# Do something
print 'A: Doing something generic'
deco = staticmethod(deco)
class B (A):
@A.deco
def do_some_B_thing(self):
# Do something
print "B: Doing something specific"
a = A()
b = B()
a.do_some_A_thing()
b.do_some_B_thing()
#Expected Output:
#A: Doing something generic
#A: Doing something generic for decoration
#B: Doing something specific
#A: Doing something generic for decoration
我現在有類型錯誤:do_some_A_thing()恰恰(給出0)1個說法。任何指針?
你試過嗎?你有錯誤嗎? – bitcycle