You need to enable JavaScript to run this app. Python循环继承问题:如何将Player类操作封装到独立Action类中
优惠活动
大模型
产品
解决方案
定价
更多

Python循环继承问题:如何将Player类操作封装到独立Action类中

解决方案

你现在的循环继承问题来自错误的继承链路设计:Action作为封装玩家操作的专用类,不需要反向继承Player,用**混入类(Mixin)**的设计模式即可满足所有需求:既可以把操作逻辑独立封装到Action类中,也能让Player正常调用Action的方法,同时Action的逻辑可以正常调用Player实例的get_account方法。

核心修改点

  • 移除Action类对Player的继承,将其作为仅提供方法的Mixin类,它只要求继承它的类实现get_account方法即可,本身无任何父类依赖,直接切断循环依赖
  • 修复原有代码的属性错误:你定义的玩家账户属性是self.account_bank,原get_account方法错误返回了不存在的self.account,会触发运行时报错

完整可运行代码

from typing import Any


class BankAccount:
    name: str
    balance: float

    def __init__(self, name: str, balance: float) -> None:
        self.name = name
        self.balance = balance


# Action作为Mixin类,不需要继承任何类
class Action:
    def buy_something(self, price):
        self.get_account().balance -= price

    def sell_something(self, price):
        self.get_account().balance += price


# Player仅继承Action即可
class Player(Action):
    name: str

    def __init__(self, **kwargs: Any) -> None:
        self.name = kwargs['name']
        self.account_bank = None

    def set_account(self, name, balance) -> None:
        self.account_bank = BankAccount(name, balance)

    # 修复属性名错误
    def get_account(self) -> BankAccount:
        return self.account_bank

    def action(self, choice, price):
        if choice == 1:
            self.buy_something(price)
        elif choice == 2:
            self.sell_something(price)
        else:
            pass


kwargs = {'name': 'jason'}
jason = Player(**kwargs)  # Create player 'jason'
jason.set_account('my_account', 100)  # Adds Jason an account with $ 100

jason.action(1, 20)  # buy something for 20 dollars
jason.action(2, 15)  # sell something for 15 dollars

# 最终余额为100-20+15=95
print(jason.get_account().balance) # 输出95

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 07:24:04