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

Question:

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.

Asked By: moonybaby

||

Answers:

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()
Answered By: Samwise
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.