我有两个班级,一个是父母,另一个是孩子。
class Parent(object):
def __init__(self):
#does something
def method_parent(self):
print "Parent"
class Child(Parent):
def __init__(self):
Parent.__init__(self)
def method_parent(self):
print "Child"
继承父级后,我想修改父方法method_parent
,保留该方法的原始功能,并为该方法添加一些额外的代码行。
我知道我可以创建一个像
这样的新方法def method_child(self):
self.method_parent()
#Add extra lines of code to perform something
但我想使用方法的原始名称。我无法复制该方法的来源,因为该方法来自C
模块
我想要实现的是这样的
def method_parent():
#do parent_method stuff
#do extra stuff
这甚至可能吗?
答案 0 :(得分:9)
您始终可以使用 super()
函数从父级调用代码。它给出了父母的参考。因此,要致电parent_method()
,您应该使用super().parent_method()
。
这是一个代码片段(用于python3),展示了如何使用它。
class ParentClass:
def f(self):
print("Hi!");
class ChildClass(ParentClass):
def f(self):
super().f();
print("Hello!");
在python2中,你需要使用额外的参数调用super:super(ChildClass, self)
。因此,该片段将成为:
class ParentClass:
def f(self):
print("Hi!");
class ChildClass(ParentClass):
def f(self):
super(ChildClass, self).f();
print("Hello!");
如果您在ChildClass实例上调用f()
,它将显示:“嗨!您好!”。
如果你已经用java编码,它基本上是相同的行为。 您可以在任何地方打电话给超级。在方法中,在init函数中,......
还有其他方法可以做到但不太干净。例如,你可以这样做:
ParentClass.f(self)
调用父类的f函数。
答案 1 :(得分:4)
这是super
函数的作用。
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
def method_parent(self):
super(Child, self).method_parent()
print "Child"
在Python 3中,您可以在没有参数的情况下调用super
,例如super().method_parent()
答案 2 :(得分:1)
您可以完全按照与__init__
之一相同的方式调用父方法:
class Child(Parent):
def __init__(self):
Parent.__init__(self)
def method_parent(self):
Parent.method_parent(self) # call method on Parent
print "Child"
这个是你想明确命名父类的时候。如果您愿意,可以让python使用super
在方法解析顺序中为您提供下一课:
def method_parent(self):
super(Child, self).method_parent() # call method on Parent
print "Child"