Assigning to self

Frans Englich frans.englich at
Mon Jan 17 13:45:46 EST 2005


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:


class foo:
        tests = {}
        def __init__( self, id ):

                        me = self.__class__.tests[ id ]

                except KeyError:
                        print "Did not exist, initializing myself.."
                        self.attr = "exists"
                        self.__class__.tests[ id ] = self

                        print "Already exists! Re-using existing instance"
                        self = me

                print "Me", self.attr   +  "!" # line 18

        def yo(self):
                return self.attr # line 21

def main():

        a = foo( "test" )
        print "ATTR:", a.yo()

        b = foo( "test" )
        print "ATTR:", b.yo()

if __name__ == "__main__":


This is the output:

Did not exist, initializing myself..
Me exists!
ATTR: exists
Already exists! Re-using existing instance
Me exists!
Traceback (most recent call last):
  File "", line 32, in ?
  File "", line 29, in main
    print "ATTR:", b.yo()
  File "", line 21, in yo
    return self.attr # line 21
AttributeError: foo instance has no attribute 'attr'

What the code attempts to do is implementing a, to the API user, transparent 
memory-saver by ensuring that no more than one instance of the class foo 
exists for a particular id. E.g, the user can simply "create" an instance and 
if one not already exists, it is created.

First of all; am I approaching the goal with the right solution?

The way I do fails, obviously. The line 'self = me'(scary..) doesn't really 
work for the attribute attr; the attribute exists on line 21, but it fails 
when yo() tries to access it. What have failed? Is it a namespace scope 
issue? Do 'self = me' do what I think it should?



More information about the Python-list mailing list