类作为函数的输入

Cur*_*arn 2 python class input

我有一个different_classes包含三个不同类的文件.它是这样的:

class first(object):
    def __init__(x, y, z):
    body of the first class

class second(first):
    def __init__(x, y, z, a=2, b=3):
    body of the second class

class third(object):
    def __init__(x, y, z):
    body of the third class
Run Code Online (Sandbox Code Playgroud)

现在我有另一个文件,说main.py我希望能够传递需要调用的类的名称.例如,我现在做:

import different_classes
def create_blah():
    instance = different_classes.first()
    rest of the function body
Run Code Online (Sandbox Code Playgroud)

当我想要使用第一堂课的时候different_classes.如果我想使用类second,我使用different_classes.second().

我可以在create_blah函数中输入类名作为参数.就像是:

def create_blah(class_type = "first", x=x1, y=y1, z=z1):
    instance = different_classes.class_type(x, y, z)
Run Code Online (Sandbox Code Playgroud)

我知道这可能无效......但想知道是否可以做类似的事情.谢谢!

Dun*_*can 10

而不是传递类的名称,为什么不直接传递类本身:

def create_blah(class_type = different_classes.first, x=x1, y=y1, z=z1):
    instance = class_type(x, y, z)
Run Code Online (Sandbox Code Playgroud)

请记住,类只是Python中的其他对象:您可以将它们分配给变量并将它们作为参数传递.

如果您确实需要使用该名称,例如因为您正在从配置文件中读取它,那么请使用它getattr()来检索实际的类:

instance = getattr(different_classes, class_type)(x, y, z)
Run Code Online (Sandbox Code Playgroud)