从i读取JSON文件并创建对象

2024-05-10 08:59:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序,随机产生10个RPG字符。我实现了将它们保存到characterFile.json的功能,该文件中包含的内容如下:

[
{
    "health": 100,
    "name": "da fu en ",
    "power": 30,
    "sAttackPwr": 60,
    "speed": 10,
    "type": "Elf"
},
{
    "health": 100,
    "name": "tuk ar da ",
    "power": 90,
    "sAttackPwr": 40,
    "speed": 50,
    "type": "Dragon"
},
{
    "health": 100,
    "name": "tuk el low ",
    "power": 30,
    "sAttackPwr": 60,
    "speed": 10,
    "type": "Elf"
},
{
    "health": 100,
    "name": "ant en ant ",
    "power": 90,
    "sAttackPwr": 40,
    "speed": 50,
    "type": "Dragon"
},
{
    "health": 100,
    "name": "tuk en el ",
    "power": 90,
    "sAttackPwr": 40,
    "speed": 50,
    "type": "Dragon"
},
{
    "health": 100,
    "name": "ar da ar ",
    "power": 90,
    "sAttackPwr": 40,
    "speed": 50,
    "type": "Dragon"
},
{
    "health": 100,
    "name": "kar ing tuk ",
    "power": 30,
    "sAttackPwr": 60,
    "speed": 10,
    "type": "Elf"
},
{
    "health": 100,
    "name": "da cha ing ",
    "power": 50,
    "sAttackPwr": 70,
    "speed": 30,
    "type": "Wizard"
},
{
    "health": 100,
    "name": "da cha low ",
    "power": 50,
    "sAttackPwr": 70,
    "speed": 30,
    "type": "Wizard"
},
{
    "health": 100,
    "name": "da cha tuk ",
    "power": 30,
    "sAttackPwr": 60,
    "speed": 10,
    "type": "Elf"
}
]

(粘贴到SO中时格式错误,但在文件中的设置方式是正确的)

我希望能够读回这个程序,从那个列表创建对象。在

到目前为止,我将文件读回程序:

^{pr2}$

characterClass是我用来实例化对象的类:

# Base Class for creating an RPG character
class character:
    # __init__ method, creates the name, type, health properties
    def __init__(self, charName, charType, charHealth):
        self.name = charName
        self.type = charType
        self.health = charHealth


class characterClass(character):
    def __init__(self, charName, charType, charHealth, charPower, charSAttackPwr, charSpeed):
        character.__init__(self, charName, charType, charHealth)
        self.power = charPower
        self.sAttackPwr = charSAttackPwr
        self.speed = charSpeed

运行此代码时,出现以下错误:

TypeError: list indices must be integers or slices, not dict

现在,我理解这个错误的方式是,我试图在一个列表中寻找一个索引,但是却把整个字典发送给它,它不能变成一个整数

为了使用循环将这个读回我的程序,我遗漏了什么?在


Tags: nameself程序inittypedaspeedpower
2条回答

这里,^{cd1>}是实际字符dict,而不是索引:

for x in data:

尝试类似的方法:

^{pr2}$

我在这里还添加了缺少的引号,我建议使用比^{{cd2>}更具描述性的名称。^{cd3>}怎么样?Python类通常以^{{cd4>}命名,因此^{{cd5>}和^{cd6>}可能比^{{cd7>}和^{{cd8>}更好。Python的official style guide在这里可能会有所帮助。

最后,我认为您不需要^{cd9>}。

x不是索引,而是dict本身。For循环遍历从JSON文件加载到数据中的每个条目。正确的代码行应该是:

gameChars = characterClass(x['name'], x['type'], x['health'], x['power'], x['sAttackPwr'], x['speed'])

相关问题 更多 >