2016-12-04 19 views
0

我試圖構建一個類來創建怪物(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) 
+0

對不起,你有什麼問題嗎? –

+0

您定義了'__init__',它有許多參數,所以你爲什麼不使用它?有沒有一個錯誤提到了7個參數,1個參數? –

+1

你應該看看一些基本的例子如何編寫類在python – pagep

回答

0
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值也會改變

+0

當我打印的清單它打印 [<__在0x101806eb8主要__。全國人大對象>,<__主要__。全國人大對象在0x101806ef0>,<__主要__。NPC處0x101806f28對象>,<__ main __。npc object at 0x101806f60>,<__ main __。npc obj etc ..... – jasonzinn7

+0

是的。預計。看看這個問題的一些信息。 http://stackoverflow.com/questions/12933964/printing-a-list-of-objects-of-user-defined-class –

相關問題