【问题标题】:How to call a function of a parent class with its own instance variables without overriding child's instances?如何在不覆盖子实例的情况下使用自己的实例变量调用父类的函数?
【发布时间】:2020-06-12 13:30:54
【问题描述】:

假设我有以下代码sn-p。

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

我怎样才能实现它?基本上是在子类中调用父类,父类应该使用自己的实例变量。

【问题讨论】:

  • 如果您希望 self.where 神奇地成为父母的 show() 中的“父母”,而在孩子的 show() 中查找时,您不能这样做,因为 @987654324 @ 是一个对象,具有一个属性where。没有两个不同的对象,父对象和子对象。也许您可以进一步编辑您的问题:您真正想要实现什么?
  • 如果您希望实例属性完全独立于 Parent 和 Child,请将其重命名为 __where。前导双下划线会导致名称根据访问它的类而被破坏:_Parent__where 来自 Parent,_Child__where 来自 Child。

标签: python python-3.x oop inheritance


【解决方案1】:

需要调用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)

【讨论】:

  • 但是请注意,如果您按照此操作,稍后的 obj.show() 将显示 Inside Child parent,我不确定这是否是任何人想要的。
  • 是的,我同意,也许他需要指定他想要实现的目标。另一方面,根据他的要求,__init__() 的调用允许实例化父级的 where 变量
【解决方案2】:

感谢@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()  

【讨论】:

  • 这(双下划线)并不是真正的私有化。它被称为name mangling。这样做的目的是防止子类意外覆盖您不想被覆盖的父类的方法。
  • @Lagerbaer 谢谢。顺便说一句,我想知道是否可以在不编写相同的 show() 函数两次的情况下实现相同的目标?
  • 是的,只需从 Child 中删除 show 并使 Parent 中的 show 更通用:print(f"Inside {type(self)}: {self.__where}")
  • @Lagerbaer 尝试过,但在这种情况下,它总是会打印 Parent 的变量 __where
【解决方案3】:

你需要记得调用超类的__init__()方法。

注意,您已将其标记为 Python3,因此您可以使用

super().__init__()
super().show()

在这种情况下,不需要在括号内使用子类的名称。

【讨论】:

  • 和@abdoBim 一样。我想先打印Inside Parent, parent
猜你喜欢
  • 2013-04-05
  • 1970-01-01
  • 2019-02-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多