说,我们有以下情况,
class A():
def something():
...
...
...
class B(A):
def use_something():
...
...
# Now, at this point I want something() to be decorated with a
# decorator. But, since it is already defined in base class,
# I am not getting how to decorate it here, in the subclass.
self.something()
...
...
现在,在B类中,我想使用A类中的something(),但我想为其应用装饰器。我无法在A类中对其进行装饰,因为我想在不同的地方应用不同的装饰器。说,类C(A),我也想在这里使用其他装饰器使用something()。
因此,回到原来的问题;如何在子类中将装饰器应用于超类的方法?
有什么特殊原因导致您不能仅仅覆盖something()
?
class A():
def something(self):
...
class B(A):
def use_something(self):
...
self.something()
...
def something(self):
# Do "decorator" stuff
super().something()
# Do more "decorator" stuff
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句