【发布时间】:2020-11-24 17:13:46
【问题描述】:
我正在尝试创建一个装饰器,该装饰器在方法被子类覆盖时扩展类方法的功能。这是一个最小的例子:
class Parent(object):
def __init__(self):
return
def say_hello(self):
print('Parent says hello')
class Child1(Parent):
def __init__(self):
super().__init__()
def say_hello(self):
print('Child says hello')
child = Child1()
child.say_hello() # this will print 'Child says hello'
我想创建一个装饰器,除了子方法之外,它还将执行父方法。
def extendedmethod(method):
def wrapper(obj):
# call the method as defined by the superclass
method(obj) # call the method defined by the subclass
return wrapper
class Child2(Parent):
def __init__(self):
super().__init__()
@extendedmethod
def say_hello(self):
print('Child says hello')
child = Child2()
child.say_hello() # I want this to print 'Parent says hello' then 'Child says hello'
我想我真正要问的是如何访问从装饰器内部派生子类的超类?
【问题讨论】:
-
你能修复你的代码吗?第一个不会打印您认为的内容,第二个甚至不会编译为字节码。另外,你知道
super吗? -
问题在于
super需要知道涉及到哪个类和对象,而编译器在extendedmethod内部无权访问这些信息。 -
我特别要求排除这是否可能是通过在方法中使用
super()在方法内解决的XY问题,而不是添加装饰器。 -
我修复了代码,对此感到抱歉。我只使用过 super 来创建对父类的引用,以便我可以调用它的构造函数。我从来没有在这个上下文之外使用过它,而且我不太了解它。如何在子类的重写方法中使用它?
-
如果您在
print('Child says hello')之前添加super().say_hello(),您将在没有装饰器的情况下获得所需的行为。这不是你想要的吗?
标签: python inheritance decorator