类作为函数的输入
我有一个文件叫 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
现在我有另一个文件,比如叫 main.py
,我想在这个文件里能够传入需要调用的类的名字。例如,现在我这样做:
import different_classes
def create_blah():
instance = different_classes.first()
rest of the function body
当我想使用 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)
我知道这可能不太有效……但我想知道有没有类似的办法可以做到。谢谢!
3 个回答
-1
可以这么说。虽然还有更复杂的方法,但我建议用这个。
def create_blah(class_type = "first", x=x1, y=y1, z=z1):
if class_type == "first":
instance=different_classes.first(x,y,z)
...
0
def create_blah(class_type = "first", x=x1, y=y1, z=z1):
class_ = different_classes.__dict__.get(class_type, None)
if isinstance(class_, type):
instance = class_(x, y, z)
你也可以把类的对象传来传去,比如这样写:class_ = different_classes.first
。
11
与其传递类的名字,不如直接传递类本身:
def create_blah(class_type = different_classes.first, x=x1, y=y1, z=z1):
instance = class_type(x, y, z)
记住,在Python中,类其实和其他对象没什么不同:你可以把它们赋值给变量,也可以把它们当作参数传来传去。
如果你确实需要使用名字,比如因为你是从配置文件中读取的,那就可以用 getattr()
来获取实际的类:
instance = getattr(different_classes, class_type)(x, y, z)