从列表创建类实例
我在用Python编程……我有一个包含名字的列表。我想用列表里的每个名字来创建一个类的实例。但是现在这些名字是字符串,不能直接用。有没有人知道怎么在循环中做到这一点?
class trap(movevariables):
def __init__(self):
movevariables.__init__(self)
if self.X==0:
self.X=input('Move Distance(mm) ')
if self.Vmax==0:
self.Vmax=input('Max Velocity? (mm/s) ')
if self.A==0:
percentg=input('Acceleration as decimal percent of g' )
self.A=percentg*9806.65
self.Xmin=((self.Vmax**2)/(2*self.A))
self.calc()
def calc(self):
if (self.X/2)>self.Xmin:
self.ta=2*((self.Vmax)/self.A) # to reach maximum velocity, the move is a symetrical trapezoid and the (acceleration time*2) is used
self.halfta=self.ta/2. # to calculate the total amount of time consumed by acceleration and deceleration
self.xa=.5*self.A*(self.halfta)**2
else: # If the move is not a trap, MaxV is not reached and the acceleration time is set to zero for subsequent calculations
self.ta=0
if (self.X/2)<self.Xmin:
self.tva=(self.X/self.A)**.5
self.halftva=self.tva/2
self.Vtriang=self.A*self.halftva
else:
self.tva=0
if (self.X/2)>self.Xmin:
self.tvc=(self.X-2*self.Xmin)/(self.Vmax) # calculate the Constant velocity time if you DO get to it
else:
self.tvc=0
self.t=(self.ta+self.tva+self.tvc)
print self
我是一名机械工程师。这个“trap”类描述了一种在我们机器设计中常见的运动模式。我们的设备里有很多独立的轴(也就是“trap”类),所以我需要通过创建独特的实例来区分它们。这个“trap”类是从“movevariables”继承来的,里面有很多像属性一样的获取和设置函数。这样,我就可以通过实例的名字来修改这些变量。我在想,能不能通过循环这个列表一次性初始化很多机器轴,而不是一个一个地输入。
5 个回答
1
如果你有一个以字符串形式表示的类列表,你可以这样做:
classes = ['foo', 'bar']
for class in classes:
obj = eval(class)
然后要创建一个实例,你只需要这样做:
instance = obj(arg1, arg2, arg3)
2
使用getattr的方法看起来是对的,下面是一些更详细的说明:
def forname(modname, classname):
''' Returns a class of "classname" from module "modname". '''
module = __import__(modname)
classobj = getattr(module, classname)
return classobj
这段内容来自Ben Snider的一篇博客文章。
2
你可以使用一个字典,像这样:
classes = {"foo" : foo, "bar" : bar}
然后你可以这样做:
myvar = classes[somestring]()
这样的话,你需要先初始化并保持这个字典,但你可以控制哪些类可以被创建。