Python3将类对象初始化为不同的变量并将它们存储在字典中

2024-05-16 17:56:38 发布

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

我正在尝试构建一个类来创建怪物(npc),然后将它们的值初始化为不同的npc[var],然后分别创建5个并将它们添加到一个列表中,然后打印列表以查看它是否存在。
我该怎么办?你知道吗

我的代码如下所示。你知道吗

class npc:
    def __init__(self, name, health, attack, defense, loot, gold):
        self.n = name
        self.h = health
        self.a = attack
        self.d = defense
        self.l = loot
        self.g = gold
class hero:
    def __init__(self, health, attack, defense, gold):

        self.health = health
        self.attack = attack
        self.defense = defense
        self.gold = gold
npc1 = npc()
npc1.name = "Goblin"; npc1.health = 10; npc1.attack = 10; npc1.defense = 10
npc1.loot= "goblin_armor"; npc1.gold = 10
npc2 = npc()
npc1.name = "Goblin"; npc1.health = 10; npc1.attack = 10; npc1.defense = 10
npc1.loot= "goblin_armor"; npc1.gold = 10
npc3 = npc()
npc1.name = "Goblin"; npc1.health = 10; npc1.attack = 10; npc1.defense = 10
npc1.loot= "goblin_armor"; npc1.gold = 10
npc4 = npc()
npc1.name = "Goblin"; npc1.health = 10; npc1.attack = 10; npc1.defense = 10
npc1.loot= "goblin_armor"; npc1.gold = 10
npc5 = npc()
npc1.name = "Goblin"; npc1.health = 10; npc1.attack = 10; npc1.defense = 10
npc1.loot= "goblin_armor"; npc1.gold = 10


monsters = []

for i in range(0,5):
    monsters.append(npc1)
for i in range(6,10):
    monsters.append(npc2)
for i in range(11,15):
    monsters.append(npc3)
for i in range(16,20):
    monsters.append(npc4)
for i in range(21,25):
    monsters.append(npc5)

print (monsters)

Tags: nameinselfforarmorhealthdefenseattack
1条回答
网友
1楼 · 发布于 2024-05-16 17:56:38
class npc:
    def __init__(self, name, health, attack, defense, loot, gold):
        self.n = name
        self.h = health
        self.a = attack
        self.d = defense
        self.l = loot
        self.g = gold

npc1 = npc()

单凭这一点就应该出错

Traceback (most recent call last):
  File "python", line 10, in <module>
TypeError: __init__() takes exactly 7 arguments (1 given)

您需要正确使用构造函数

npc1 = npc("Goblin", 10, 10, 10, "goblin_armor", 10)
print(npc1.n) # Goblin

注意:npc1.n是变量,因为您设置了self.n而不是self.name。。。变量可以是多个字母


或者根本不用构造函数

class npc:
  pass

npc2 = npc()
npc2.name = "Goblin"; npc2.health = 10; npc2.attack = 10; npc2.defense = 10
npc2.loot= "goblin_armor"; npc2.gold = 10

print(npc2.name) # Goblin

如果使用第二种方法,则需要设置npc2的值,而不是npc1。你知道吗

npc2 = npc()
npc1.name = "Goblin"; npc1.health = 10; npc1.attack = 10; npc1.defense = 10
npc1.loot= "goblin_armor"; npc1.gold = 10

然后,您需要在添加到列表时创建新实例,而不是添加同一对象的多个副本。你知道吗

monsters = []

for i in range(0,5):
    next_npc = npc(<values_here>)
    monsters.append(next_npc)

否则,如果您编辑了monsters[0].name,那么monsters[1:4].name值也会更改

相关问题 更多 >