如何调用 class 构造函数,其名称在文本变量中? [Python]

How to call class constructor having its name in text variable? [Python]

假设我们在全局命名空间中定义了一些 类 并且可用。例如:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Vector:
    def __init__(self, alpha, r):
        self.x = r * cos(alpha)
        self.y = r * sin(alpha)

# and many others...

如何操作:

class_name = 'Point'
x = 14.361
y = -8.100
code_str = 'class_object = ' + class_name + '(' + str(x) + ', ' + str(y) + ')'

exec code_str  # That evaluates to: "class_object = Point(14.361, -8.100)"

print class_object.x, class_object.y

不使用危险的执行程序?

PS。如果有人问,我打算从一些 txt 或 json 文件中加载数据。

如果在全局命名空间中定义(或导入)class,您可以通过 globals() 返回的字典获取对它的引用。之后,只需以通常的方式创建一个实例,例如:

class_name = 'Point'
kwargs = {'x': 14.361, 'y': -8.100}
Point = globals()[class_name]
point = Point(**kwargs)

如果 class 是在同一个模块中定义或导入的,您可以使用类似的东西:

globals()[class_name](x, y)

如果你有很多class要处理,你最好用字典来存储它们,键是名字,值是class,

然后你可以调用它:

my_classes = {'Point' : Point, 'Point2' : Point2}

class_name = 'Point'
x = 14.361
y = -8.100
my_classes[class_name](x, y)

您可以使用 eval。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Vector:
    def __init__(self, x, y):
        self.x = x+100
        self.y = y+100

class_name = 'Vector'

x = 10
y = 20
caller = '{}({},{})'.format(class_name,x,y)
ob = eval(caller)

print ob.x, ob.y