简体   繁体   English

创建类实例

[英]Creating class instances

Could someone please explain to me how to create class instances from a list (or a string that might be fetched from excel). 有人可以向我解释如何从列表(或可能从excel中获取的字符串)创建类实例。 I always seem to run into this problem. 我似乎总是遇到这个问题。 I want to create many instances of classes and then save them in a shelve later. 我想创建许多类的实例,然后将它们保存在货架上。

This sample code doesn't work, but illustrates the approach I'm trying. 此示例代码不起作用,但是说明了我正在尝试的方法。

class test:
  def __init__(self):
      self.a='name'

if _name__=='__main__':
   list=['A','B']
   for item in list:
       item=test()

Few issues in your code includes naming of variables. 您的代码中很少有涉及变量命名的问题。 It can confuse you. 它会使您感到困惑。

class test:
    # I guess you want to provide the name to initialize the object attribute
    def __init__(self, name):   
        # self.name is the attribute where the name is stored.
        # I prefer it to self.A 
        self.name = name        

Now the issue here is that instance is also a element of your list, which I presume is a name. 现在的问题是,实例也是您列表中的一个元素,我认为这是一个名称。

if __name__=='__main__':
    # I presume these are list of names
    list_of_names = ['A','b','c']

    # You have to store your instance some where.
    instance_list = []

    # Here name is an element of the list that you are iterating
    # I change it to name instead of instance
    for name in list_of_names:   
        # Here I am appending to the list, a test object that I create         
        instance_list.append(test(name))

[Edit:] [编辑:]

Now, I truly don't understand you, why this piece of code: 现在,我真的不了解您,为什么这段代码:

  for item in list:
       item=class()   # How can you reassign the item ? 

See what this item is . 看看这是什么。

>>> for item in ['A', 'B']:
...     print item
... 
A
B
>>> 

You should not assign it item = .... but you should use it .... = ..(item) !!! 您不应将其分配为item = ....但应使用它为.... = ..(item) !!!

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

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