Home > Mobile >  How do you create an instance of a class using a function in Python?
How do you create an instance of a class using a function in Python?

Time:12-06

Something like this:

def new_instance(class_name):
    return instance_of_class

E.g. if I had a Dog class, I could write d = new_instance(Dog) and d would now refer to a new Dog object.

Obviously I can write d = Dog() but I'd like to pass in the class as a parameter to the init method of another class.

CodePudding user response:

A class is just a named object like any other, so you can pass it as an argument to a function just as easily as you'd pass any other object.

def new_instance(cls):
    return cls()
d = new_instance(Dog)  # same as d = Dog()
  • Related