Instantiate Subclass From Superclass
Solution 1:
use @classmethod
instead of @staticmethod
:
classSuperclass(object):
@classmethoddefget_instance(cls):
#This should return an instance of subclass1 or subclass2return cls()
classSubclass1(Superclass):
passclassSubclass2(Superclass):
pass
Solution 2:
If you want to access the list of subclasses of a given class you can use the __subclasses__
method:
>>>classMyClass(object):...pass...>>>classSubclass1(MyClass):...pass...>>>classSubclass2(MyClass):...pass...>>>MyClass.__subclasses__()
[<class '__main__.Subclass1'>, <class '__main__.Subclass2'>]
If you already know the existing subclasses you can simply instantiate them directly:
>>>classMyClass(object):...defgetInstance(self):...return Subclass1()...>>>classSubclass1(MyClass): pass...>>>MyClass().getInstance()
<__main__.Subclass1 object at 0x1e72d10>
Anyway, I guess that you are trying to implement the Singleton pattern, in which case I think you should not use a getInstance
method at all. Just implement it using:
- a module, since modules are singletons
- Reimplementing
__new__
to return the old instance, if an instance already exist - Using some metaclass
And there are a lot more ways of doing this.
If this is not your aim, then maybe you ought to change design because super-class usually do not have to know about subclasses.
Solution 3:
The correct way to do this, if you cannot just call selfclass()
in a classmethod, is to define (or assume) a factory method, and have your superclass method call that factory method on self
:
classMixinator(object):
@classmethod # this is not really necessary, but it means you don't need an instance to start withdeffactoryuser(selfclass, *args):
return selfclass.factory(*args)
#only define factory if you want Mixinator to be usable on its own @classmethoddeffactory(selfclass, *args):
return selfclass(*args) # this is a stub.
Obviously, child classes should need to have something more involved in their factory
to make this worthwhile. I'm not sure there's any use-case that can't be solved by replacing factory
with an appropriate __new__
, but this is more explicit.
Post a Comment for "Instantiate Subclass From Superclass"