如何调用在文本变量中具有名称的类构造函数? [蟒蛇] [英] How to call class constructor having its name in text variable? [Python]
本文介绍了如何调用在文本变量中具有名称的类构造函数? [蟒蛇]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们定义了一些类,并且这些类在全局名称空间中可用。例如:
Let's assume we have some classes defined and available in global namespace. In example:
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
而不使用危险的执行程序?
without using the dangerous exec?
PS。如果有人问,我打算从一些txt或json文件中加载数据。
PS. I'm intending to load the data from some txt or json file if anyone asks.
推荐答案
如果已定义或导入了该类在同一模块中,您可以使用类似以下内容的东西:
If the class is defined or imported in the same module, you could use something like :
globals()[class_name](x, y)
如果要处理的类很多,最好使用字典来存储它们,键是名称,值是该类,
if you have many classes to handle, you should better use a dictionnary to store them, key is the name, value is the class,
然后您可以使用以下命令来调用它:
then you can call it with :
my_classes = {'Point' : Point, 'Point2' : Point2}
class_name = 'Point'
x = 14.361
y = -8.100
my_classes[class_name](x, y)
这篇关于如何调用在文本变量中具有名称的类构造函数? [蟒蛇]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文