假设我有以下代码片段。
class Parent():
def __init__(self):
self.where = 'parent'
def show(self):
print("Inside Parent", self.where)
class Child(Parent):
def __init__(self):
self.where = 'child'
super(Child, self).show()
self.show()
def show(self):
print("Inside Child", self.where)
# Driver's code
obj = Child()
但是输出是
Inside Parent, child
Inside Child, child
我希望输出恰好为(希望首先打印父项(
Inside Parent, parent
Inside Child, child
我怎样才能做到这一点?基本上,它是在父类应该使用自己的实例变量的子类中调用父类。
您需要调用Parent类的__init__()
函数:
class Parent():
def __init__(self):
self.where = 'parent'
def show(self):
print("Inside Parent", self.where)
class Child(Parent):
def __init__(self):
self.where = 'child'
self.show()
super().__init__()
super().show()
def show(self):
print("Inside Child", self.where)
感谢@jasonharper,它非常简单。问题是将where
私有化为父类和子类中的__where
变量。
class Parent():
def __init__(self):
self.__where = 'parent'
def show(self):
print("Inside Parent", self.__where)
class Child(Parent):
def __init__(self):
self.__where = 'child'
super().__init__()
super().show()
self.show()
def show(self):
print("Inside Child", self.__where)
# Driver's code
obj = Child()
您需要记住调用超类的__init__()
方法。
注意,你已经将其标记为Python3,所以你可以只使用
super().__init__()
super().show()
在这种情况下,不需要在括号内使用子类的名称。