I'm confused about the following. The idea here is that the set of instances of some class are small and finite, so I'd like to create them at class creation time, then hijack __new__ to simply return one of the preexisting classes instead of creating a new one each call.

This seems to work in python3, but fails in python2 with:

    Foo(23)
TypeError: unbound method __Foo__new__() must be called with Foo instance as first argument (got type instance instead)

I don't understand.  Can anyone explain?

--rich
class Foo(object):
    def __init__(self, val):
        self.val = val

foos = [Foo(0), Foo(1)]

def __Foo__new__(cls, val):
    if val & 0x1:
        return foos[0]
    else:
        return foos[1]

Foo.__new__ = __Foo__new__

Foo(23)
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to