python - Resetting class to default state -
in python, standard/commonly used way reset class "default state"? example, before loading class might want reset existing data.
for example, check out self.clear()
method below:
class conlanguage: serializable_attributes = \ ["roots", "prefixes", "suffixes"...] #list of "important" fields def __init__(self): self.roots = [] self.prefixes = [] self.suffixes = [] ..... def clear(self): # <<--- method tmp = conlanguage() attr in self.serializeable_attributes: setattr(self, attr, getattr(tmp)) def loadfromdict(self, indict): defaultvalues = conlanguage() attr in self.serializable_attributes: setattr(self, attr, indict.get(attr, getattr(defaultvalues.attr))) def loads(self, s): self.loadfromdict(json.loads(s))
this approach seems job, wonder if there way it.
the other question (which not have accepted answers) seems cover diferrent problem - has couple of numerical fields needs initialized zero, while in scenario there bunch of members have different default state - dictionaries, arrays, numbers, strings, etc.
so less "how iterate through class attributes" , more about: "does python have commonly used paradigm particular situation". accessing attributes names using strings doesn't seem quite right.
if changed seriaizable_attributes
dict
containing attributes , default values, avoid initializing temporary instance copy attributes, , initialize object calling clear well, in case there's no code duplication.
class foo: serializable_attributes = { 'belongings' : list, 'net_worth' : float } def __init__(self): self.clear() def clear(self): k, v in serializable_attributes.items(): setattr(self, k, v())
Comments
Post a Comment