Python多重继承整合Buy/Sell类时属性被覆盖,如何实现嵌套结构?
问题描述
我尝试通过以下代码将Buy和Sell两个类整合到isCash类中:
class Buy: def __init__(self, buy_value: float, buy_currency: str) -> None: self.buy_value = buy_value self.buy_currency = buy_currency class Sell: def __init__(self, sell_value: float, sell_currency: str) -> None: self.sell_value = sell_value self.sell_currency = sell_currency class isCash(Buy,Sell): def __init__(self, buy_value, buy_currency,sell_value, sell_currency) -> None: super().__init__(buy_value, buy_currency) super().__init__(sell_value,sell_currency) obj1 = isCash(Buy(1,"mnt"),Sell(2,"mnt")) print(obj1.__dict__)
运行结果为:
{'buy_value': 2, 'buy_currency': 'mnt'}
可以看到Sell类的属性被覆盖丢失了,请问如何实现如下嵌套字典结构的实例属性?
{ "buy": { "buy_value": 1, "buy_currency": "MNT" }, "sell": { "sell_value": 1, "sell_currency": "MNT" }, }
解决方案
核心思路:用组合替代多继承
原代码的问题出在多继承的使用方式上:super().__init__()只会调用继承链中优先级最高的类(这里是Buy)的构造方法,两次调用会直接覆盖同一批属性。改用组合(将Buy和Sell实例作为isCash的属性)可以完美实现嵌套结构。
方法1:直接传入实例构建嵌套结构
class Buy: def __init__(self, buy_value: float, buy_currency: str) -> None: self.buy_value = buy_value self.buy_currency = buy_currency class Sell: def __init__(self, sell_value: float, sell_currency: str) -> None: self.sell_value = sell_value self.sell_currency = sell_currency class isCash: def __init__(self, buy_obj: Buy, sell_obj: Sell) -> None: self.buy = buy_obj self.sell = sell_obj # 创建实例并输出嵌套字典 obj1 = isCash(Buy(1, "mnt"), Sell(1, "mnt")) print({ "buy": obj1.buy.__dict__, "sell": obj1.sell.__dict__ })
运行结果:
{'buy': {'buy_value': 1, 'buy_currency': 'mnt'}, 'sell': {'sell_value': 1, 'sell_currency': 'mnt'}}
方法2:在类内部创建子实例并提供字典转换方法
如果希望直接通过isCash的参数来构建,无需提前创建Buy/Sell实例,可以这样写:
class Buy: def __init__(self, buy_value: float, buy_currency: str) -> None: self.buy_value = buy_value self.buy_currency = buy_currency class Sell: def __init__(self, sell_value: float, sell_currency: str) -> None: self.sell_value = sell_value self.sell_currency = sell_currency class isCash: def __init__(self, buy_value: float, buy_currency: str, sell_value: float, sell_currency: str) -> None: self.buy = Buy(buy_value, buy_currency) self.sell = Sell(sell_value, sell_currency) # 新增方法直接返回目标嵌套字典 def to_nested_dict(self): return { "buy": self.buy.__dict__, "sell": self.sell.__dict__ } # 创建实例并调用方法输出 obj1 = isCash(1, "mnt", 1, "mnt") print(obj1.to_nested_dict())
运行结果与预期完全一致。
内容的提问来源于stack exchange,提问作者Battseren Badral
相关产品推荐
相关产品推荐

