Assigning to self

Paul McGuire ptmcg at austin.rr._bogus_.com
Mon Jan 17 20:13:34 CET 2005


<wittempj at hotmail.com> wrote in message
news:1105988333.379592.327600 at z14g2000cwz.googlegroups.com...
> An implementation of what you want can be found here:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558
>
I think this recipe pre-dates the introduction of __new__ in Python.

How about something like this (requires the name to be the first constructor
argument):
-------------------------------------------
class RegisteredObject(object):
    registry = {}
    def __new__(cls,name,*args,**kwargs):
        if name not in cls.registry:
            cls.registry[name] = object.__new__(cls)
        return cls.registry[name]

class foo (RegisteredObject):
    def __init__(self,name):
        self.myName = name

    def yo(self):
        return self.myName

def main():

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

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

        c = foo( "test2" )
        print "ATTR:", c.yo()
        print id(c)

if __name__ == "__main__":
        main()
----------------------------------------------
gives:
ATTR: test
7886256
ATTR: test
7886256
ATTR: test2
7887984

-- Paul





More information about the Python-list mailing list