【发布时间】:2018-11-23 15:37:39
【问题描述】:
我是在 Python 中使用 JSON 的新手。我有一个程序可以生成 10 个具有多个属性的字符(对象)。我正在使用 Python JSON 库将这些写入文件:
def saveCharsToFile(gameChars):
# Using a WITH operator for easy readability. creating and opening a file
# in write mode
with open("characterFile.json", "w") as write_file:
# using the json.dump function to take the objects in the gameChars
# list and serialise it into JSON
json.dump([x.__dict__ for x in gameChars], write_file)
# Tells the User that the file has been written
print("File 'characterFile.json' has been written to...")
以下是生成字符的其中一种类的示例:
# A subclass for creating a Wizard character, inherits the Character class
# and adds the power, sAttackPwr, and speed properties
class wizard(character):
def __init__(self, CharPower, CharSAttackPwr, CharSpeed):
# Getting the properties from the inheritted character Base Class
character.__init__(self, "W", 100)
self.power = CharPower
self.sAttackPwr = CharSAttackPwr
self.speed = CharSpeed
# Base Class for creating an RPG character
class character:
# __init__ method, creates the name, type, health properties
def __init__(self, charType, charHealth):
self.name = rndName()
self.type = charType
self.health = charHealth
这是使用 saveCharsToFile 保存的文件的内容:
[{"name": "ing low fu ", "type": "B", "health": 100, "power": 60, "sAttackPwr": 10, "speed": 60}, {"name": "en ar da ", "type": "W", "health": 100, "power": 50, "sAttackPwr": 70, "speed": 30}, {"name": "ar fu fu ", "type": "B", "health": 100, "power": 70, "sAttackPwr": 20, "speed": 50}, {"name": "da low en ", "type": "W", "health": 100, "power": 50, "sAttackPwr": 70, "speed": 30}, {"name": "da fu cha ", "type": "D", "health": 100, "power": 90, "sAttackPwr": 40, "speed": 50}, {"name": "da ing el ", "type": "W", "health": 100, "power": 50, "sAttackPwr": 70, "speed": 30}, {"name": "cha kar low ", "type": "D", "health": 100, "power": 90, "sAttackPwr": 40, "speed": 50}, {"name": "ar da el ", "type": "D", "health": 100, "power": 90, "sAttackPwr": 40, "speed": 50}, {"name": "da da ant ", "type": "B", "health": 100, "power": 60, "sAttackPwr": 10, "speed": 60}, {"name": "el ing kar ", "type": "B", "health": 100, "power": 70, "sAttackPwr": 20, "speed": 50}]
我希望能够将其作为列表读回程序中,最好将它们实例化为具有上面该列表中字符属性值的对象。
这是我将文件读回程序的当前方式:
def openCharsToFile(gameChars):
with open("characterFile.json") as read_file:
y = json.load(read_file)
for x in y:
gameChars.insert[x, y]
for z in gameChars:
print(z.getStats())
但是当我运行这个程序时,我得到了以下错误:
Traceback (most recent call last):
File "rpgProblemSolving.py", line 342, in <module>
main()
File "rpgProblemSolving.py", line 338, in main
openCharsToFile(gameChars)
File "rpgProblemSolving.py", line 305, in openCharsToFile
gameChars.insert[x, y]
TypeError: 'builtin_function_or_method' object is not subscriptable
如果有人有任何建议,将不胜感激,谢谢
【问题讨论】:
标签: python json python-3.x list object