Something like this:
def new_instance(class_name):
return instance_of_class
Eg 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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.