Rishin S Babu Rishin S Babu - 1 month ago 8
Python Question

Getting to know which derived class got instantiated in the base class constructor

In the base class constructor I need to know which of its derived classes got instantiated. The base class is a db Class which connects to mongo and each of the derived classes represents a collection object. I am creating the mongo connection in the base class constructor and there I need to know the name of collection I will be dealing with in that particular instance.

Answer

The more robust way would be to simply pass an argument to the base constructor. That way, you have no coupling with the subclass or its name. And you could even subclass subclasses without breaking the functionality in the base class:

class BaseModel:
    def __init__ (self, collectionName):
        self.connection = createConnection(collectionName)

class MyModel (BaseModel):
    def __init__ (self):
         super().__init__('MyModel')

Other than that, the object passed as self is already a proper instance, so you could do whatever you want with it, to figure out its type.

Comments