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

Python如何访问字典中子类实例继承的父类属性值

代码错误原因

你现在的代码有3个核心问题,导致国家相关的属性没法正常访问:

  1. Country类的get_Name、get_population方法缩进错误,目前是类外的全局函数,根本不属于Country类,实例无法调用
  2. City子类调用父类构造方法的写法完全错误:你写的Country.__init__(Country, CountryPopulation)第一个参数传的是传入的国家名字符串,不是当前City实例,父类构造根本没给City实例绑定国家相关属性
  3. 子类构造的参数名和父类名重名(参数也叫Country),很容易引发引用混淆。
修正后的可运行代码
class Country:
    def __init__(self, Name, Population):
        self.Name = Name
        self.Population = Population

    # 修正缩进,把方法放到类内部
    def get_Name(self):
        print(self.Name)

    def get_population(self):
        return self.Population


class City(Country):
    def __init__(self, cityName, Citypopulation, CountryName, CountryPopulation):
        self.cityName = cityName
        self.Citypopulation = Citypopulation
        # 用super()调用父类构造,自动传入当前实例self,不需要手动传
        super().__init__(CountryName, CountryPopulation)
        # 做属性名映射,匹配你期望的.Countrypopulation访问方式
        self.Countrypopulation = self.Population
        self.CountryName = self.Name


Cities = {
    "Japan" : City("Tokyo", "13.6M", "Japan", "125.8M"),
    "England": City("London", "9M", "England", "55.98M"),
    "US": City("New York", "8.3M", "US", "329.5M")
}

# 原有打印城市名的逻辑不受影响
for x in Cities:
    print(Cities[x].cityName)

print("=== 国家信息输出 ===")
# 你期望的国家人口访问逻辑可正常运行
for x in Cities:
    print(Cities[x].Countrypopulation)

# 也可以直接访问国家名称
for x in Cities:
    print(Cities[x].CountryName)
入门提示
  • Python类的所有成员方法必须和__init__方法保持统一缩进,否则不会被识别为类的方法
  • 子类调用父类构造优先用super().__init__(参数)的写法,不需要硬编码父类名,也不需要手动传self参数,能避免很多传参错误
  • 如果父类定义的属性名和你业务里想调用的名字不一致,直接在子类构造里加一行简单赋值做别名即可,不需要修改父类代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 03:39:23