Home > OS >  Creating class object inside same class in Python
Creating class object inside same class in Python

Time:12-13

I'm trying to create a class object inside the class itself, something like this:

 class Motor:
 
 #other code here

     def function(self):
            x = Motor()

This works and runs correctly, but if I use inheritance to create another class as a daughter of this one (e.g. Car(Motor)), the Car.function() doesn't work properly because it's creating an object of type Motor, not Car. Is there any other way I could do this?

Thanks!!

CodePudding user response:

You'll want to receive the class to instantiate as an argument to the method, rather than hard-coding the class name.

class Motor:
    @classmethod
    def function(cls):
        x = cls()
        ...

If this is really something that needs to be an instance method, you can use type(self) instead.

class Motor:
    def function(self):
        x = type(self)()
  • Related