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

Python中类间共享属性/变量问题:代码触发NameError错误

Python类之间共享属性的方法及代码错误分析解决

错误原因分析

  • Base类__init__方法里的a = "baseclass"是局部变量,仅在该函数内部有效,不会成为实例的属性,因此ChildB中直接引用a会触发NameError。
  • ChildA中的b = "child a"同样是局部变量,仅属于ChildA的__init__函数作用域,ChildB的实例无法访问该变量。

类间共享属性的正确方式

要在父类与子类、不同子类之间共享属性,常用两种实现方式:

1. 绑定为实例属性(self.xxx)

将变量绑定到实例对象上,所有继承自父类的子类实例都能通过self访问这些属性。

修改后的示例代码:

class Base(object):
    def __init__(self):
        print("Base created")
        # 将a绑定为实例属性
        self.a = "baseclass"

class ChildA(Base):
    def __init__(self):
        super(ChildA, self).__init__()
        # 将b绑定为实例属性
        self.b = "child a"

# 让ChildB继承ChildA,才能访问b属性
class ChildB(ChildA):
    def __init__(self):
        super(ChildB, self).__init__()
        self.c = "child b"
        # 通过self访问实例属性
        print(self.a)
        print(self.b)

ChildA()
ChildB()

执行输出:

Base created
Base created
baseclass
child a

2. 定义为类属性

如果属性无需每个实例单独维护,所有类的实例共享同一值,可以直接在类级别定义属性。

示例代码:

class Base(object):
    # 类属性,所有子类实例共享
    a = "baseclass"
    def __init__(self):
        print("Base created")

class ChildA(Base):
    # ChildA的类属性
    b = "child a"
    def __init__(self):
        super(ChildA, self).__init__()

class ChildB(Base):
    def __init__(self):
        super(ChildB, self).__init__()
        self.c = "child b"
        # 访问类属性,可通过类名或self
        print(Base.a)
        print(ChildA.b)
        print(self.a)

ChildB()

执行输出:

Base created
baseclass
child a
baseclass

关键总结

  • 局部变量仅在定义它的函数内部有效,无法跨类/实例访问。
  • 实例属性(self.xxx)属于单个实例,子类实例可通过继承访问父类的实例属性。
  • 类属性属于类本身,所有该类及子类的实例共享同一值,修改类属性会影响所有实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:06:17