Python __iadd__ TypeError: unsupported operand type(s) for +=

Python __iadd__ TypeError: unsupported operand type(s) for +=

我正在构建一个战斗模拟程序。 运行 进入类型错误。无法解决。任何帮助,将不胜感激。我似乎无法使 iadd 函数正常工作。我正在尝试使用 python 中的 iadd 函数将新的 Pokemon 对象添加到现有的 PokemonTrainer 对象。有人对如何执行此操作有任何想法吗?

main.py

name = input("State your name: ")
player = PokemonTrainer(name)

player += Pokemon("Staryu", ElementType.WATER, [
    Move("water blast", ElementType.WATER, 5),
    Move("water cyclone", ElementType.WATER, 6)
    ])

pokemon_trainer.py

对于iadd,我使用基于类型的调度来处理参数。如果它是 Pokemon 类型,调用 self 上的 add_pokemon 方法,然后 return self 对象。如果它是 Item 类型,则调用 self 上的 add_item 方法,然后 return self 对象。否则,引发 TypeError。

from pokemon import Pokemon

class PokemonTrainer:

    def __init__(self, name, pokemon = [], items = [], current_active_pokemon = None):
        self.name = name
        self.pokemon = pokemon
        self.items = items
        self.current_active_pokemon = current_active_pokemon


    def __iadd__(self, other):

        self.pokemon.append(other)

        if (type(other) == type(Pokemon)):
            self.add_pokemon(other)

        elif (type(other) == type(Item)):
            self.add_item(other)

        else:
            raise TypeError("Only Pokemon or Item type are allowed")

        return self

    def add_pokemon(self, pkmn):

        self.pokemon.append(pkmn)

        if (self.current_active_pokemon == None):
            self.current_active_pokemon = pkmn


    def add_item(self, item):

        self.items.append(item)

pokemon.py

class Pokemon:

    def __init__(self, name, pokemon_type, moves):
        self.name = name
        self.pokemon_type = pokemon_type
        self.moves = moves

        self.level = 1
        self.exp = 0
        self.max_hp = 100
        self.current_hp = self.max_hp
        self.attack_power = 1
        self.defense_power = 1
        self.fainted = False

我猜你想要 isinstance(other, Pokemon) 而不是 type(other) == type(Pokemon)

https://docs.python.org/3/library/functions.html#isinstance

此处也相关:What are the differences between type() and isinstance()?