Reputation: 19807
I want to keep a dictionary of my custom classes so that I can dynamically instantiate them from other dictionaries (loaded from db), but I'm not sure what to store.
class_register = {}
class Foo(object):
def __init__(self, **kwargs):
class_register[self.__class__.__name__] = ?? # what to store here?
self.__dict__.update(kwargs)
new_instance = class_register[result['class_name']](**result['data'])
Open to any suggestions.
Upvotes: 0
Views: 447
Reputation: 365
I would inherit them off the same base class and then request __subclasses__()
of that class, once I was sure they were all done. Perhaps in the form:
Base.class_register = dict((x.__name__, x) for x in Base.__subclasses__())
It uses less magic to let Python do the bookkeeping.
Also, if they do not have enough in common to have this superclass seem warranted, you would probably have trouble using them in the same code after construction in any way that was not confusing.
Upvotes: 2
Reputation: 375604
Just store the class itself:
class_register[self.__class__.__name__] = self.__class__
But this is a bit of overkill, since you are registering the class every time you instantiate it.
Better is to use this:
def register(cls):
class_register[cls.__name__] = cls
class Foo(object):
# blah blah
register(Foo)
And then you can turn this into a class decorator to use like this:
def register(cls):
class_register[cls.__name__] = cls
return cls
@register
class Foo(object):
# blah blah
Upvotes: 2