0
Does anyone know how to serialize in YAML or JSON a class that contains attributes that contain other classes?
Class player has the Spellbook attribute (class that returns a magic list) and the Backpack attribute (class that returns another list that contains the items, etc.) that are subclasses of a list.
class Player:
def __init__(self,name='', *args, **kwargs):
super().__init__(*args, **kwargs)
self._name = name
self.spellbook = Spellbook(unit=self)
self.base_damage = 0
self.backpack = Backpack()
self.level = 0
self.stats = {'strength': 1, 'inteligence': 1}
self.stats_points = 5
self._up_experience = 0
self._experience = 0
self._max_health = 0
self._health = 0
self.max_mana = 0
self._mana = 0
self.base_mana_regeneration = 0
self._mana_regeneration = 0
self.potions = 4
self._defense = 0
self.base_defense = 0
self.live_status = True
self._gold = 0
self._score = 0
self.equipped_items = {
'weapon': None,
'shield': None,
'head': None,
'chest': None,
'legs': None,
'boots': None,
}
self._level_up()
Always when it will serialize it returns this error:
TypeError: Object of type Heal is not JSON serializable
In such case the error is talking about the Spell(Heal) you have in Spellbook, but it shows the same problem regarding the items.
This post here has a guy who gives an example similar to what I need, but the code didn’t work on me, it’s in an infinite loop.
@Edit1
Function that returns the attributes it contains in the player.
def save_data(player):
data = {}
for attr in player.__dict__:
data[attr] = player.__dict__[attr]
return data
Function that saves the file.
def save_char(self, char):
from game.units import save_data
json.dump(save_data(char), open(f'saves/{char.name}.json', 'w'))
How do you have it serialized? This code has to be in the question.
json.dumps
which is the normal way to serialize things in JSON does not work for class instances.– jsbueno
It’s exactly the json.dumps I’m using.
– Thomas Caio
(know that you can press the button
{}
to format the code here and preserve the indentation, right? Or delimite the code with three ``` - but fix the indentation - indentation in Python is not only "cute" - its above code snippets are all syntax errors, and that takes away people who might want to answer)– jsbueno
I still don’t know the platform commands well. I hadn’t even noticed that I was out of identation. Thank you!
– Thomas Caio