You need to enable JavaScript to run this app. Python子类继承父类双下划线私有属性报错原因及修复方案
优惠活动
大模型
产品
解决方案
定价
更多

Python子类继承父类双下划线私有属性报错原因及修复方案

报错原因

Python中以双下划线__开头的类属性会触发**名称改写(Name Mangling)**机制:Python会自动将属性名转换为_类名__属性名的格式,目的是避免子类与父类的同名属性冲突,是Python实现私有属性的默认机制。

  • 父类Shape中定义的__color、__filled属性,实际存储的名称为_Shape__color、_Shape__filled
  • 子类Circle中直接访问self.__color时,Python会默认查找名称为_Circle__color的子类私有属性,而非父类改写后的属性
  • 除此之外,你原来的super().__init__调用写死了固定参数color="yellow", filled=True,并未将子类初始化传入的blue、False传递给父类构造函数,哪怕没有名称改写问题,父类存储的属性值也不符合预期

以上三点就是你删除子类中两行赋值代码后报错的根本原因。

正确修改方案

方案1:将双下划线私有属性改为约定私有(推荐)

Python中约定单下划线_开头的属性为类内部私有属性,不会触发名称改写机制,适合有继承需求的场景:

def main() :
    a = Shape()
    b = Shape("red")
    print(a,b)
    c = Circle("blue",False,10)
    print(c)
    print(c.area())

class Shape:
    def __init__(self, color="yellow", filled=True):
        # 改为单下划线,避免名称改写
        self._color = color
        self._filled = filled

    def __str__(self):
        return f'({self._color},{self._filled})'

class Circle(Shape):
    def __init__(self, color="yellow", filled=True, radius=0):
        # 修正super调用,将参数透传给父类构造
        super().__init__(color, filled)
        self.__radius = radius

    def area(self):
        fullArea = 3.14*((self.__radius)**2)
        return fullArea

    def __str__(self):
        # 直接复用父类的__str__实现,减少重复代码
        return super().__str__() + f'(radius = {self.__radius})'

main()

方案2:保留双下划线私有属性,适配名称改写规则

如果你必须保留父类的双下划线私有属性定义,可以直接调用父类已实现的方法,或访问父类改写后的属性名:

class Circle(Shape):
    def __init__(self, color="yellow", filled=True, radius=0):
        # 修正super调用,将参数透传给父类构造
        super().__init__(color, filled)
        self.__radius = radius

    def area(self):
        fullArea = 3.14*((self.__radius)**2)
        return fullArea

    def __str__(self):
        # 方式1:直接调用父类__str__方法,无需硬编码改写后的属性名(更推荐)
        return super().__str__() + f'(radius = {self.__radius})'
        # 方式2:直接访问父类改写后的属性名
        # return f'({self._Shape__color},{self._Shape__filled})(radius = {self.__radius})'

两种方案运行后均可得到你预期的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 13:15:04