简体   繁体   English

从列表创建类实例

[英]creating class instances from a list

Using python.....I have a list that contain names. 使用python .....我有一个包含名称的列表。 I want to use each item in the list to create instances of a class. 我想使用列表中的每个项目来创建类的实例。 I can't use these items in their current condition (they're 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'm a mechanical engineer. 我是机械工程师。 The trap class describes a motion profile that is common throughout the design of our machinery. 疏水阀类别描述了整个机械设计中常见的运动曲线。 There are many independent axes (trap classes) in our equipment so I need to distinguish between them by creating unique instances. 我们的设备中有许多独立的轴(陷阱类),因此我需要通过创建唯一的实例来区分它们。 The trap class inherits from movevariables many getter/setter functions structured as properties. trap类从movevariables继承了许多构造为属性的getter / setter函数。 In this way I can edit the variables by using the instance names. 这样,我可以使用实例名称来编辑变量。 I'm thinking that I can initialize many machine axes at once by looping through the list instead of typing each one. 我在想可以通过遍历列表而不是键入每个轴来一次初始化许多机床轴。

You could use a dict, like: 您可以使用dict,例如:

classes = {"foo" : foo, "bar" : bar}

then you could do: 那么您可以执行以下操作:

myvar = classes[somestring]()

this way you'll have to initialize and keep the dict, but will have control on which classes can be created. 这样,您将必须初始化并保留字典,但是可以控制可以创建哪些类。

The getattr approach seems right, a bit more detail: getattr方法似乎是正确的,但有更多细节:

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 Snider . 摘自Ben Snider的博客文章

If it a list of classes in a string form you can: 如果它是字符串形式的类列表,则可以:

classes = ['foo', 'bar']
for class in classes:
    obj = eval(class)

and to create an instance you simply do this: 并创建一个实例,您只需执行以下操作:

instance = obj(arg1, arg2, arg3)

EDIT 编辑

If you want to create several instances of the class trap, here is what to do: 如果要创建类陷阱的多个实例,请执行以下操作:

namelist=['lane1', 'lane2']
traps = dict((name, trap()) for name in namelist)

That will create a dictionary that maps each name to the instance. 这将创建一个字典,将每个名称映射到实例。

Then to access each instance by name you do: 然后通过名称访问每个实例,您可以执行以下操作:

traps['lane1'].Vmax

您可能正在寻找getattr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM