Explicitly creating a new object in Python
Question: I am trying to create new objects and store them in a dictionary. But it
doesn't seem to be working the way I expect.

    
    
    class Fruit:
       name = ''
       facts = []
       def __init__(self, FruitName):
           self.name = FruitName
           facts = []
       def addfact(self, FruitName):
           if FruitName == 'banana':
               self.facts.append('bananas contain potassium')
           elif FruitName == 'orange':
               self.facts.append('These are some facts about oranges')
           else:
               self.facts.append('Unrecognized fruit submitted')
    
    Files = ['banana', 'orange', 'apple']
    
    ObjLibrary = {}
    
    for File in Files:
        if not File in ObjLibrary:
            ObjLibrary[File] = Fruit(File)
        ObjLibrary[File].addfact(File)
    
    print ObjLibrary['banana'].facts
    print ObjLibrary['orange'].facts
    print ObjLibrary['apple'].facts
    

I get the following output:

    
    
    ['bananas contain potassium', 'These are some facts about oranges', 'Unrecognized fruit submitted']
    ['bananas contain potassium', 'These are some facts about oranges', 'Unrecognized fruit submitted']
    ['bananas contain potassium', 'These are some facts about oranges', 'Unrecognized fruit submitted']
    

Now I suspect what's going on is that I'm not explicitly creating three
objects the way I want, but just pointing all three items in the dictionary to
the same object. My question is: why? On each pass of the loop, `File` should
have a different value. More importantly, how to I get around it? In my "real"
code, it's not practical to create a totally new variable to store each
object.

Thanks for your help.

Casey


Answer: The problem is that `facts` is a class variable, not an instance one. You
should define it inside `__init__` (and remove the useless local variable
declaration there):

    
    
    class Fruit:
    
       def __init__(self, FruitName):
           self.name = FruitName
           self.facts = []
    
       def addfact(self, FruitName):
           ...
    

Note Python is not Java, there is no need to "declare" attributes at the class
level.

