假设我们在全局命名空间中定义了一些可用的类。在示例中:
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
不使用危险的执行程序?
附言。如果有人询问,我打算从某些 txt 或 json 文件加载数据。
如果该类是在同一模块中定义或导入的,则可以使用类似以下内容的内容:
globals()[class_name](x, y)
如果你有很多类要处理,你最好使用字典来存储它们,键是名称,值是类,
然后你可以用以下方式调用它:
my_classes = {'Point' : Point, 'Point2' : Point2}
class_name = 'Point'
x = 14.361
y = -8.100
my_classes[class_name](x, y)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)