首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python3将类对象初始化为不同的变量并将其存储在字典中

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

Stack Overflow用户
提问于 2016-12-04 08:38:13
回答 1查看 49关注 0票数 0

我正在尝试构建一个类来创建怪物(Npc),然后将它们的值初始化为不同的npcvar,然后创建每个npcvar的5个,并将它们添加到一个列表中,然后打印该列表以查看它是否存在。

我该怎么做呢?

我的代码如下所示。

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2016-12-04 08:48:48

代码语言:javascript
复制
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()

仅此一项就会出现以下错误

代码语言:javascript
复制
Traceback (most recent call last):
  File "python", line 10, in <module>
TypeError: __init__() takes exactly 7 arguments (1 given)

您需要正确使用构造函数。

代码语言:javascript
复制
npc1 = npc("Goblin", 10, 10, 10, "goblin_armor", 10)
print(npc1.n) # Goblin

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

或者根本不使用构造函数

代码语言:javascript
复制
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

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

代码语言:javascript
复制
monsters = []

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40954146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档