I have following code:
class EntityBase (object) :
__entity__ = None
def __init__ (self) :
pass
def entity (name) :
class Entity (EntityBase) :
__entity__ = name
def __init__ (self) :
pass
return Entity
class Smth (entity ("SMTH")) :
def __init__ (self, a, b) :
self.a = a
self.b = b
# added after few comments -->
def factory (tag) :
for entity in EntityBase.__subclasses__ () :
if entity.__entity__ == tag :
return entity.__subclasses__ ()[0]
raise FactoryError (tag, "Unknown entity")
s = factory ("SMTH") (1, 2)
print (s.a, s.b)
# <--
Now in factory I can get all subclasses of EntityBase, find concrete subclass for “SMTH” and create it.
Is this valid approach or maybe I something misunderstood and doing wrong?
I would do this with a decorator. Also, storing the entity -> subclass map in a dictionary lets you replace a linear scan with a dict lookup.
I’m not sure if the
__entity__attribute is actually useful to you of if you were just using it to implement the linear scan. I left it in but if you took it out, then the classes associated with entity wouldn’t even need to inherit fromEntityBaseand you could rename it to something likeRegistry. This shallows up your inheritance tree and opens the possibility of using on classes that aren’t related through common descent.Depending on what your use case is, a better way to do it might just be
The decorator is fancier and let’s us feel nice and fancy about ourselves but the dictionary is plain, useful and to the point. It is easy to understand and difficult to get wrong. Unless you really need to do something magic, then I think that that’s the way to go. Why do you want to do this, anyway?