我正在尝试构建一个类来创建怪物(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)
单凭这一点就应该出错
您需要正确使用构造函数
注意:
npc1.n
是变量,因为您设置了self.n
而不是self.name
。。。变量可以是多个字母或者根本不用构造函数
如果使用第二种方法,则需要设置
npc2
的值,而不是npc1
。你知道吗然后,您需要在添加到列表时创建新实例,而不是添加同一对象的多个副本。你知道吗
否则,如果您编辑了
monsters[0].name
,那么monsters[1:4].name
值也会更改相关问题 更多 >
编程相关推荐