如何让子类继承父类属性?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
相关产品推荐
相关产品推荐

