我試圖構建一個類來創建怪物(npc),然後將它們的值初始化爲不同的npc [var],然後創建5個並將它們添加到一個列表,然後打印列表以查看它是否存在。
我該怎麼處理?Python3將類對象初始化爲不同的變量並將它們存儲在字典中
我的代碼如下所示。
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)
對不起,你有什麼問題嗎? –
您定義了'__init__',它有許多參數,所以你爲什麼不使用它?有沒有一個錯誤提到了7個參數,1個參數? –
你應該看看一些基本的例子如何編寫類在python – pagep