首页 > 解决方案 > 如何使用对类实例值的引用来迭代列表?

问题描述

我正在用python制作一个冒险游戏,我有一个剑类 - 我有一个函数,它的目的是在列表中找到最强大的剑(我稍后会修改这个函数作为玩家库存,但是无关)。我不断收到“int类型不可迭代”的错误,这对我来说很奇怪,因为当它只是一个数字而不是对类实例中的值的引用时,它似乎适用于其他人. 有人可以帮我弄这个吗?谢谢!

class Sword:
    def __init__(self, name=None, strength=None, description=None):
        self.name = name
        self.strength = strength
        self.description = description


rusty_sword = Sword(
    name="rusty sword",
    strength=5,
    description="This is a rusty old sword that you found on the ground.",
)
gold_sword = Sword(
    name="gold sword",
    strength=15,
    description="This is a fine golden sword, with a crown engraved on the handle.",
)
diamond_sword = Sword(
    name="diamond sword",
    strength=45,
    description="This 100% pure diamond sword is of the finest quality. It reflects a prism of light when you turn it back and forth.",
)
plasma_sword = Sword(
    name="plasma sword",
    strength=135,
    description="This plasma sword can slay any opponent. With this, you are unstoppable.",
)


def mostpowerfulsword():
all_swords = (rusty_sword, gold_sword, diamond_sword, plasma_sword)
for sword in all_swords:
    swordstrength = sword.strength
    print(max(swordstrength))

标签: pythonlistmax

解决方案


您正在调用的max函数swordstrengthint. 您在循环的每次迭代中覆盖swordstrength值。我怀疑你想建立一个列表并将其传递给max函数。

所以你应该改变你的mostpowerfulsword函数看起来像这样:

def mostpowerfulsword():
    all_swords = (rusty_sword, gold_sword, diamond_sword, plasma_sword)
    swordstrengths = []
    for sword in all_swords:
        swordstrengths.append(sword.strength)
    print(max(swordstrengths))

推荐阅读