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

如何让子类继承父类属性?Python类继承问题求助

修正Python类继承代码以适配现有调用逻辑

你当前的代码在类继承的构造方法调用上存在错误,没有正确让子类继承父类的属性,以下是修正后的代码(严格保留if __name__ == '__main__':下方的代码不变):

class Country:
    def __init__(self, country_capital, president):
        self.country_capital = country_capital
        self.president = president

class State(Country):
    def __init__(self, state_capital, governor, c):
        # 调用父类Country的构造方法,传入已有Country实例的属性
        super().__init__(c.country_capital, c.president)
        self.state_capital = state_capital
        self.governor = governor

class County(State):
    def __init__(self, county_seat, c):
        # 调用父类State的构造方法,传入已有State实例的属性和关联的Country实例
        super().__init__(c.state_capital, c.governor, c)
        self.county_seat = county_seat

if __name__ == '__main__':
    United_States = Country("Washington, DC", "Joe Biden")
    Kentucky = State("Frankfort", "Andy Beshear", United_States)
    Jefferson = County("Louisville", Kentucky)
    print("County seat: ", Jefferson.county_seat)
    print(" Governor: ", Jefferson.governor)
    print("State capital: ", Jefferson.state_capital)
    print("Country capital: ", Jefferson.country_capital)
    print("President:", Jefferson.president)

关键修改说明

  • State类修正:

    • 用super().__init__(c.country_capital, c.president)调用父类构造方法,直接复用传入的Country实例的属性,实现父类属性继承。
    • 移除错误的空Country实例创建代码,避免覆盖传入的有效实例。
  • County类修正:

    • 用super().__init__(c.state_capital, c.governor, c)调用父类State的构造方法,传入已有State实例的所有必要属性,确保County能继承State和Country的全部属性。
    • 删除错误的空State实例创建和参数错误的super()调用代码,修正构造逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:41:00