I am using a nested class for "book keeping" purposes in Python 3. The class structure (highly simplified) looks something like this:
class BookKeeping:
class ItemA:
count = 0
item_list = []
@classmethod
def add(cls, item_a):
cls.count += 1
cls.item_list.append(item_a)
class ItemB:
count = 0
item_dict = {}
...
This class makes it convenient to keep track and to access some "global" properties of a system I am modelling. Having nested classes allows for clear namespacing. For instance, in any module I can ... import BookKeeping as BK
and check how many ItemB
objects there are (BK.ItemB.count
).
At some point in my program I would like to "reset" all class attributes, i.e. I would like to set BookKeeping.ItemA.count
to 0 again and empty lists and dictionaries, etc.
Obviously, I could add a top-level class method like BookKeeping.reset()
which resets all values "manually", like:
class BookKeeping:
@classmethod
def reset(cls):
cls.ItemA.count = 0
cls.ItemA.item_list = []
cls.ItemB.count = 0
...
However, this seems to be an error-prone approach to me and it involves "maintenance" of this class (I might forget to reset some attributes). Please note, my real class is more complicated than the example I have provided.
What is the easiest way to reset all class attributes to their original state at runtime?
BookKeepingSession
or something) that holds those values as instance properties rather than class properties? Then you could just create a freshBookKeepingSession
each time you want to do some unrelatedBookKeeping
. – Daniel Pryden