简体   繁体   English

如何在 Python 中使用 function 创建 class 的实例?

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

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.例如,如果我有一只狗 class,我可以写d = new_instance(Dog)并且d现在指的是一条新狗 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.显然我可以写d = Dog()但我想将 class 作为参数传递给另一个 class 的 init 方法。

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. class 与其他名称一样只是一个名为 object 的名称,因此您可以将其作为参数传递给 function,就像传递任何其他 object 一样容易。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM