字典和课堂

2024-05-17 15:22:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

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)

在python3中我该如何做呢?你知道吗


Tags: nameself密码initdeftypedescriptionclass
3条回答

正如@MSeifert所说。不管怎样,遍历字典会为每个项提供键和值。所以这也是可行的:

for key, value in WEAPONS.items():
    print(value.Name)

顺便问一下:你为什么用字典?因为每种武器都有自己的名字。你知道吗

只需迭代values

for item in WEAPONS.values():
    print(item.Name)

最好是在类(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()
        }

会给你想要的输出。你知道吗

相关问题 更多 >