【问题标题】:Why Super() in Python not taking Parent Class Instance variable in Child class为什么 Python 中的 Super() 不采用子类中的父类实例变量
【发布时间】:2021-08-28 15:00:28
【问题描述】:

我是 OOP 的新手 在 Python 中,我试图通过使用超级方法“super()”来访问实例方法的实例变量,并且我尝试了多种可能性,但我发现每当我使用访问实例时变量我得到 AttributeError

我的代码

class P:

    def m1(self):

        self.b=10

class C(P):

    def __init__(self):

        super().m1()

        print(super().b)

c=C()

class P:

    a=888

    def m1(self):

        self.a=10

**输出:**

Traceback (most recent call last):

  File "D:\myPractice.py\sideRun.py", line 9, in <module>

    c=C()

  File "D:\myPractice.py\sideRun.py", line 7, in __init__

    print(super().b)

AttributeError: 'super' object has no attribute 'b'

-----------------------------------------------------------

但是每当我尝试使用 self 访问 Instance 变量时,我都会得到我想要的输出。

我的代码


class C(P):

    def __init__(self):

        super().m1()

        print(super().a)

        print(self.a)
c=C()

输出

888

10

我的问题:

为什么 super() 方法不允许内部系统访问实例变量?

【问题讨论】:

    标签: python python-3.x class object oop


    【解决方案1】:

    那是因为super().m1()self.m1() 的功能相同,这意味着它将属性b 设置为C 类

    class P:
    
        def m1(self):
    
            self.b=10
    
    class C(P):
    
        def __init__(self):
    
            super().m1()
    
            print(self.b)
    
    c=C()
    

    这将打印10

    【讨论】:

      猜你喜欢
      • 2019-05-07
      • 1970-01-01
      • 2018-07-07
      • 2019-02-01
      • 2013-06-20
      • 2023-03-28
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      相关资源
      最近更新 更多