【问题标题】:How to access show method in parent class from child class?如何从子类访问父类中的show方法?
【发布时间】:2019-09-28 19:40:35
【问题描述】:
class Parent:
    def __init__(self):
        self.__num = 100

    def show(self):
        print("Parent:",self.__num)

class Child(Parent):  
    def __init__(self):
        self.__var = 10
    def show(self):
        super().show()
        print("Child:",self.__var)   

obj1 = Child()
obj1.show()

文件“main.py”,第 12 行,在节目中
超级().show()
文件“main.py”,第 6 行,在 show
print("父母:",self.__num)
AttributeError: 'Child' 对象没有属性 '_Parent__num'

【问题讨论】:

  • super().__init__() 添加到您的构造函数中
  • 不要使用双下划线变量,它们会受到名称修改的影响,您应该先熟悉它。
  • @KlausD。刚刚添加了这个作为答案......

标签: python oop


【解决方案1】:

您需要在子类中初始化父实例,因为__num 属性仅在Parent 的初始化期间设置,而不是在Child 的初始化期间设置。

class Child(Parent):  
    def __init__(self):
        super().__init__()
        self.__var = 10
    def show(self):
        super().show()
        print("Child:",self.__var)   

【讨论】:

    【解决方案2】:
    class Parent:
        def __init__(self):
            self.__num = 100
    
        def show(self):
            print("Parent:",self.__num)
    
    class Child(Parent):  
        def __init__(self):
            super().__init__()  # Solution
            self.__var = 10
    
        def show(self):
            super().show()
            print("Child:",self.__var)   
    
    obj1 = Child()
    obj1.show()
    

    【讨论】:

      【解决方案3】:

      为了避免覆盖,试试这个。

      class Parent:
        def __init__(self):
          self.__num = 100
      
        def show(self):
           print("Parent:",self.__num)
      
      class Child(Parent):  
        def __init__(self):
           Parent.__init__(self)
           self.__var=10
        def show1(self):
          print("Child:",self.__var)   
      
      obj1 = Child()
      obj1.show()
      

      【讨论】:

        【解决方案4】:

        将您的 Child.init 更改为:

        def __init__(self):
            self.__var = 10
            super().__init__()
        

        【讨论】:

          【解决方案5】:

          正如其他答案已经说过的那样,您需要将 super().__init__() 添加到您的子类的 __init__ 中。

          但还要注意,这里有一个叫做 name mangling 的东西在起作用。阅读例如 3。双前导下划线:this page 上的 __var

          简短的版本是:如果您想在子类中也使用属性self.__num,则应将其重命名为self._num(仅一个下划线)。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-07-09
            • 1970-01-01
            • 2017-09-22
            • 1970-01-01
            • 2017-10-12
            • 1970-01-01
            • 2014-10-04
            相关资源
            最近更新 更多