【发布时间】:2016-12-31 03:59:38
【问题描述】:
说,我们有以下情况,
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(),使用不同的装饰器。
所以,回到原来的问题;如何将装饰器应用于子类中的超类方法?
【问题讨论】:
-
为什么你需要“应用一个装饰器”而不是仅仅用子类特定的代码来包装
A.method()调用,不管装饰器会做什么?请举例说明您希望做什么。 -
@BrenBarn 你能否对“包装方法”有所了解,或者请指导我,因为我是这些概念的新手。
-
不,我不能,直到你展示一个你想要这个假设代码做什么的例子。它可以是“假”代码(即,实际上不起作用的代码)。但是您需要展示一个具体示例来说明您希望实现的目标。
-
@BrenBarn 我已经更新了 OP。请检查。
-
newSomething = decorator(self.something)然后是newSomething()——但你可以(也应该)将装饰器中的逻辑直接放入子类中。
标签: python inheritance python-decorators