python - 如何使用对类实例值的引用来迭代列表?
问题描述
我正在用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))
解决方案
您正在调用的max
函数swordstrength
是int
. 您在循环的每次迭代中覆盖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))
推荐阅读
- tensorflow - 线性回归器 - clip_gradients_by_norm - 语法无效
- java - 如何调试 Spring Boot @ConfigurationProperties?
- python - 使用 PANDAS 中的 value_counts() 零出现/频率
- xamarin.forms.listview - 我正在尝试从安卓模拟器发送请求。但是应用程序没有提供正确的输出并在 client.sendasync 上中断
- angular - 如果在angular2中编辑后具有值,如何保持字段启用
- django - 芹菜看不到任务
- javascript - 如何根据条件创建一个新数组将元素定位在第一个位置?
- javascript - 如何操作谷歌图表以获取 haxis 中的随机图例
- html - 从表格行中的输入插入数据
- wso2 - WSO2 CEP 水平可扩展性