我需要从具有 .__str__()
方法的类列表中获取一个字符串。
所以 potions 是 Potion 类对象的列表。 Potion __str__
方法只返回药水的名称。
我想到了做这样的事情
result = "\n".join(potions)
但只能连接字符串,我不知道如何为连接中的每个类调用 __str__()
。
或者我应该这样做:
for potion in potions:
result += "{0}\n".format(potion)
或者可能是别的东西?
最佳答案
result = "\n".join(str(potion) for potion in potions)
也就是说,使用生成器表达式(也可以使用列表理解 --
result = "\n".join([str(potion) for potion in potions])
为 potions
中的每个 potion
调用 str()
。
关于python - 我可以加入类(class)列表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8823076/