I\'m trying to find the actual class of a django-model object, when using model-inheritance.
Some code to describe the problem:
class Base(models.mod
It feels brittle because it is. (This is a reprint of an answer in a different context. See C++ casting programmatically : can it be done ?)
Read up on polymorphism. Almost every "dynamic cast" situation is an example of polymorphism struggling to be implemented.
Whatever decision you're making in the dynamic cast has already been made. Just delegate the real work to the subclasses.
You left out the most important part of your example. The useful, polymorphic work.
When you said "I want to determine if the object is of type Child_1 or Child_2..." you left out the "so I can make the object do aMethod()
in a way that's unique to each subclass". That method is the useful work, and it should simply be a method of both subclasses.
class Base(models.model):
def aMethod(self):
# base class implementation.
class Child_1(Base):
def aMethod(self):
# Child_1 override of base class behavior.
class Child_2(Base):
def aMethod(self):
supert( Child_2, self ).aMethod() # Invoke the base class version
# Child_2 extension to base class behavior.
Same method, multiple implementations. Never a need to "run-time type identification" or determining the concrete class.