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

Python中如何对比存在继承关系的两个子类的属性异同

Python 子类指定属性对比实现方法

核心实现逻辑

你需要对比的是两个子类实例/类的make、model属性值,核心思路是:

  • 先指定需要对比的属性列表
  • 分别读取两个类/实例对应属性的取值
  • 逐一比对后分类存储相同和不同的属性内容

针对你现有代码的实现方案

你当前的子类__init__方法会覆盖父类传入的make、model参数,因此直接实例化后比对即可,示例代码如下:

# 先实例化两个子类对象
truck_obj = truck("任意值", "任意值")
car_obj = cars("任意值", "任意值")

# 指定要对比的属性
compare_attrs = ["make", "model"]
same_attributes = {}
diff_attributes = {}

# 遍历比对
for attr in compare_attrs:
    truck_val = getattr(truck_obj, attr)
    car_val = getattr(car_obj, attr)
    if truck_val == car_val:
        same_attributes[attr] = truck_val
    else:
        diff_attributes[attr] = (truck_val, car_val)

# 输出结果
print("两个子类相同的属性内容:", same_attributes)
print("两个子类不同的属性内容:", diff_attributes)

运行结果

两个子类相同的属性内容: {'make': 'ford'}
两个子类不同的属性内容: {'model': ('F-150', 'mustang')}

代码优化建议

你当前的子类实现中,传入的make、model参数会被硬编码值覆盖,完全没有生效。如果需要固定子类的品牌型号,建议写成类属性,不用实例化就可以直接比对属性,更合理:

class vehicles:
    def __init__(self, make, model):
        self.make = make
        self.model = model

class truck(vehicles):
    # 固定为类属性
    make = "ford"
    model = "F-150"
    def __init__(self):
        super().__init__(self.make, self.model)

class cars(vehicles):
    # 固定为类属性
    make = "ford"
    model = "mustang"
    def __init__(self):
        super().__init__(self.make, self.model)

# 无需实例化直接对比类属性
print("相同属性:", [attr for attr in ["make", "model"] if getattr(truck, attr) == getattr(cars, attr)])

内容的提问来源于stack exchange,提问作者reagent -52

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:27:03