Assigning to self

Mark McEahern marklists at mceahern.com
Mon Jan 17 14:02:04 EST 2005


Frans Englich wrote:

>Hello,
>
>I am having trouble with throwing class instances around. Perhaps I'm 
>approaching my goals with the wrong solution, but here's nevertheless a 
>stripped down example which demonstrates my scenario:
>  
>
[snip]

The basic problem seems to be that you're trying to avoid creating a new 
instance in __init__--which is too late.  By that point, the new object 
is already created.  Rebinding the name self in __init__ doesn't do what 
you seem to think it will.  Basically, you need to move the "only create 
this object if it doesn't already exist"  logic outside of __init__.

Here's an alternative approach:

#!/usr/bin/env python

class Item:
    def __init__(self, name):
        self.name = name

class Factory:

    items = {}
    def getItemByName(self, name):
        item = Factory.items.get(name)
        if not item:
            item = Item(name)
            Factory.items[name] = item
        return item

def main():
    factory = Factory()
    name = 'foo'
    for x in range(10):
        i = factory.getItemByName(name)
        print i
    print len(factory.items)

if __name__ == "__main__":
    main()




More information about the Python-list mailing list