Python 如何使用自己的实例变量调用父类的函数,而不重写子';什么样的例子?
假设我有以下代码段Python 如何使用自己的实例变量调用父类的函数,而不重写子';什么样的例子?,python,python-3.x,oop,inheritance,Python,Python 3.x,Oop,Inheritance,假设我有以下代码段 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).
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
我希望输出准确地(希望先打印父级)
我怎样才能做到呢?基本上是在子类中调用父类,父类应该使用自己的实例变量 您需要调用父类的
\uuuu init\uuu()
函数:
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)
您需要记住调用超类的
\uuu init\uuu()
方法
注意,您已经将其标记为Python3,因此您可以使用
super().__init__()
super().show()
在本例中,不需要在括号内使用子类的名称。多亏了@jasonharper,这非常简单。问题是将
where
私有化为每个父类和子类中的\uu 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()
但是,请注意,如果您遵循此操作,稍后的obj.show()将在子级父级中显示
,我不确定这是否是任何人都想要的。是的,我同意,也许他需要指定他想要实现的目标。另一方面,在他提出的问题中,\uuu init\uuu()
的调用允许实例化parents的where
变量,如果您希望self.where神奇地成为parents show()中的“parent”和child show()中的“child”,您不能这样做,因为self
是一个对象,并且有一个属性where
。没有两个不同的对象,父对象和子对象。也许您可以进一步编辑您的问题:您实际上想要实现什么?如果您希望实例属性对于父级和子级完全独立,请将其重命名为\uu where
。前导的双下划线会导致名称被损坏,具体取决于访问它的类:\u Parent\u where
来自Parent,\u Child\u where
来自Child。它与@abdoBim相同。我想在Parent内部,Parent
首先打印。这(双下划线)不是真正的私有化。这叫名字弄乱。这样做的目的是防止子类意外地重写不希望被重写的父类的方法。@lagerber谢谢。顺便说一句,我想知道我是否可以在不编写两次相同的show()
函数的情况下实现同样的功能?是的,只要从Child
中删除show
,并使Parent
中的show
更加通用:打印(f“Inside{type(self)}:{self where}”)
@lagerber尝试过,但在这种情况下,它将始终打印父变量\uu其中
。
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()