类作为函数的输入

时间:2010-12-21 16:19:24

标签: 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

现在我有另一个文件,比如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 个答案:

答案 0 :(得分:10)

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

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)

答案 1 :(得分: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

答案 2 :(得分:-1)

排序。 Thare是比较好的方式,但我建议这样做。

def create_blah(class_type = "first", x=x1, y=y1, z=z1):
    if class_type == "first":
        instance=different_classes.first(x,y,z)
    ...
相关问题