开发者

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). I always seem to run into this problem. I want to crea开发者_如何转开发te 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) !!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜