我有这段代码:
class weapon():
def __init__(self, Name, Type, Description):
self.Name=Name
self.Type=Type
self.Description=Description
WEAPONS = { "starterSword":weapon("Starter Sword", "Sword", "A short, stunt steel sword."),
"basicSword":weapon("Basic Sword", "Sword", "A basic steel sword.")
}
我想做这样的事情:
for item in WEAPONS:
print(self.Name)
我将如何在Python 3中进行此操作?
答案 0 :(得分:5)
迭代values:
for item in WEAPONS.values():
print(item.Name)
答案 1 :(得分:1)
正如@MSeifert所说。无论如何,迭代字典为您提供每个项目的关键和价值。所以这也有效:
for key, value in WEAPONS.items():
print(value.Name)
顺便问一下:你为什么要用字典?因为每个武器都有自己的名字。
答案 2 :(得分:1)
最好在类中编写方法(OOP)并调用它们而不必编写大量代码,例如。
class weapon():
def __init__(self, Name, Type, Description):
self.Name=Name
self.Type=Type
self.Description=Description
def printDetails(self):
print (self.Name)
WEAPONS = { "starterSword":weapon("Starter Sword", "Sword", "A short, stunt steel sword.").printDetails(),
"basicSword":weapon("Basic Sword", "Sword", "A basic steel sword.").printDetails()
}
将为您提供所需的输出。