我正在尝试构建一个类来创建怪物(Npc),然后将它们的值初始化为不同的npcvar,然后创建每个npcvar的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)发布于 2016-12-04 08:48:48
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.defence= 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值也会更改
https://stackoverflow.com/questions/40954146
复制相似问题