回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我有一个程序,随机产生10个RPG字符。我实现了将它们保存到<code>characterFile.json</code>的功能,该文件中包含的内容如下:</p>
<pre><code>[
{
"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"
}
]
</code></pre>
<p>(粘贴到SO中时格式错误,但在文件中的设置方式是正确的)</p>
<p>我希望能够读回这个程序,从那个列表创建对象。在</p>
<p>到目前为止,我将文件读回程序:</p>
^{pr2}$
<p><code>characterClass</code>是我用来实例化对象的类:</p>
<pre><code># 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
</code></pre>
<p>运行此代码时,出现以下错误:</p>
<pre><code>TypeError: list indices must be integers or slices, not dict
</code></pre>
<p>现在,我理解这个错误的方式是,我试图在一个列表中寻找一个索引,但是却把整个字典发送给它,它不能变成一个整数</p>
<p>为了使用循环将这个读回我的程序,我遗漏了什么?在</p>