You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python继承中无法访问父类属性,构造函数调用问题求助

Python继承中构造函数未自动初始化基类属性的问题

我正在学习Python的继承机制以及构造函数的工作原理。根据参考书籍,基类的构造函数应自动被子类继承,但运行代码时仍出现错误。

class teacher:
    def __init__(self):
        self.std=10
class student(teacher):
    def __init__(self):
        pass
s=student()
print(s.std)

运行程序时出现以下错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In [41], line 8
      6         pass
      7 s=student()
----> 8 print(s.std)

AttributeError: 'student' object has no attribute 'std'

问题原因

当子类显式定义了自己的__init__构造函数时,Python不会自动调用基类的__init__方法。你在student类中重写了__init__但未触发父类的构造逻辑,导致父类中初始化的self.std属性没有被创建,因此访问时抛出AttributeError。

解决方案

方案1:显式调用父类构造函数(推荐)

在子类的__init__中使用super()函数调用父类的构造方法,这是Python面向对象编程的标准做法:

class teacher:
    def __init__(self):
        self.std=10
class student(teacher):
    def __init__(self):
        super().__init__()  # 调用父类构造函数初始化属性
        pass
s=student()
print(s.std)  # 输出:10

方案2:直接通过父类名调用构造函数

也可以直接使用父类名称调用其__init__方法,需要传入子类实例self:

class teacher:
    def __init__(self):
        self.std=10
class student(teacher):
    def __init__(self):
        teacher.__init__(self)  # 显式调用父类构造
        pass
s=student()
print(s.std)  # 输出:10

方案3:移除子类自定义的__init__

如果子类不需要添加任何自定义的初始化逻辑,可以直接不定义__init__,此时Python会自动调用父类的构造函数:

class teacher:
    def __init__(self):
        self.std=10
class student(teacher):
    pass  # 自动继承父类的__init__
s=student()
print(s.std)  # 输出:10

内容的提问来源于stack exchange,提问作者ScaredyCat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:50:25