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

Python继承中如何仅修改父类的width初始化参数

Python继承中如何仅修改父类的width初始化参数

看起来你在继承类的时候踩了个参数传递的小坑,咱们先拆解下问题出在哪:

先看你写的代码:

class window1():
    def __init__(self,height=2,width=9):
        self.height = height
        self.width = width

class window2(window1):
    def __init__(self,width):
        super().__init__(width)

a = window2(100)
print(a.height)  # 实际输出100,不是你想要的默认2
print(a.width)   # 实际输出9,不是你想要的100

问题就出在super().__init__(width)这一行!父类window1的__init__方法里,第一个参数是height,第二个才是width。你直接把100作为位置参数传进去,相当于把这个值给了height,而width还是用的默认值9,完全搞反了逻辑。

要实现“只修改width,保留height默认值”的需求,你只需要在调用父类构造方法时明确指定参数名就行,这样就不会搞混参数位置了。修改后的window2类可以写成这样:

class window2(window1):
    def __init__(self, width):
        # 用关键字参数指定width,height自动沿用父类的默认值2
        super().__init__(width=width)

如果你想更直白地写出height的默认值,也可以这么写:

class window2(window1):
    def __init__(self, width):
        super().__init__(height=2, width=width)

现在再运行测试代码:

a = window2(100)
print(a.height)  # 输出2,符合预期
print(a.width)   # 输出100,符合预期

简单总结下:当父类构造方法有多个带默认值的参数时,如果你只想覆盖其中某一个,用关键字参数传递是最稳妥的方式,能彻底避免位置参数带来的混淆。

备注:内容来源于stack exchange,提问作者Zack

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 10:28:13