The transition from a base class to a derived class is usually a sign of poor design in the program. The method you suggest using hasattr can be a serious problem. I will show you:
# defined in some open source library class MyObject(object): def what_is_derived(self): if hasattr(self, 'derived1'): return 'derived1' elif hasattr(self, 'derived2'): return 'derived2' else: return 'base'
Suppose the classes Derived1 and Derived2 defined in the same library. Now you want to use the MyObject functions, so you get it in your own code.
# defined in your own code class MyBetterObject(MyObject): pass better_object = MyBetterObject() better_object.what_is_derived()
The whole point of polymorphism is that you can have many derived classes without changing the base class. By making the base class aware of all its derived classes, you will seriously reduce the usefulness of such a class. You cannot create a derived class without changing the base class.
Either you want to work with a derived class, or you donβt care what a particular class is, and all you need is the properties / methods of the base class. This is the same in all OOP languages. It is possible to find out what a derived class is, but this is usually a bad idea.
From the point of view of django models, I usually use inheritance like this:
class Address(models.Model):
Deeply nested inheritance chains with django models are inconvenient. In most cases, they are also not needed. Instead of polluting your base class with hasattr checks, define a helper method that can query the required derived classes if such a thing is required. Just don't define it in the Base class.
Josh Smeaton
source share