首页 > 解决方案 > 为什么 Python 中的 Super() 不采用子类中的父类实例变量

问题描述

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

我的代码

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() 方法不能使内部系统访问实例变量?

标签: pythonpython-3.xclassobjectoop

解决方案


那是因为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


推荐阅读