Instantiating a class from a list
Using python ..... I have a list containing the names. I want to use every item in the list to create instances of the class. I cannot use these items in their current state (they are strings). Does anyone know how to do this in a loop.
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
I am a mechanical engineer. The trap class describes a motion profile that is common to the entire design of our equipment. Our hardware has many independent axes (trap classes), so I need to differentiate between them by creating unique instances. The trap class inherits many getter / setter functions from movevariables, structured like properties. This way I can edit the variables using the instance names. I think I can initialize many axes of the machine at once by going through the list rather than printing each one.
Getattr's approach seems to be correct, in a little more detail:
def forname(modname, classname):
''' Returns a class of "classname" from module "modname". '''
module = __import__(modname)
classobj = getattr(module, classname)
return classobj
From a blog post by Ben Snyder .
source to share
EDIT
If you want to create multiple instances of a class hook, here's what to do:
namelist=['lane1', 'lane2']
traps = dict((name, trap()) for name in namelist)
This will create a dictionary that maps each name to an instance.
Then to access each instance by name, you do:
traps['lane1'].Vmax
source to share