SigTerm
SigTerm

Reputation: 26419

Resetting class to default state

In Python, what is standard/commonly used way to reset class to "default state"? For example, before loading something to class you might want to 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): # <<--- this method
        tmp = ConLanguage()
        for attr in self.SERIALIZEABLE_ATTRIBUTES:
            setattr(self, attr, getattr(tmp))

    def loadFromDict(self, inDict):
        defaultValues = ConLanguage()
        for 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 to do the job, but I wonder if there is another way to do it.


The other question (which does not have accepted answers) seems to cover diferrent problem - it has couple of numerical fields that needs to be all initialized with zero, while in this scenario there are bunch of members that have different default state - dictionaries, arrays, numbers, strings, etc.

So it was less about "how do I iterate through class attributes" and more about: "does python have commonly used paradigm for this particular situation". Accessing attributes by their names using strings doesn't seem quite right.

Upvotes: 1

Views: 1233

Answers (1)

Patrick McLaren
Patrick McLaren

Reputation: 988

If you changed SERIAIZABLE_ATTRIBUTES to a dict containing the attributes and their default values, you could avoid initializing a temporary instance to copy the attributes, and initialize the object by calling clear as well, in which case there's no code duplication.

class Foo:
  SERIALIZABLE_ATTRIBUTES = {
    'belongings' : list,
    'net_worth' : float
  }

  def __init__(self):
    self.clear()

  def clear(self):
    for k, v in SERIALIZABLE_ATTRIBUTES.items():
      setattr(self, k, v())

Upvotes: 1

Related Questions