Overwriting 'self' in constructor?

Alex Martelli aleaxit at yahoo.com
Tue Oct 10 15:35:52 EDT 2000


"Costas Malamas" <cmalamas at nyx10.nyx.net> wrote in message
news:971191786.371306 at irys.nyx.net...
> I apologize if this is a newbie question, but I RTFM'ed to no avail:
>
> I am trying to extend a class that produces an object in two steps: the
> constructor produces a factory object and then there is a method that
> returns the object I really want, i.e.: A.make().  Now, I want to extend
> A, but I'd like to get the second type of object from the constructor.
> Python (1.52, 1.6, Win32) won't let me do this:
>
> class B(A):
>    def __init__(self):
>       A.__init__(self)
>       self = A.make(self)
>
> The product of this is _always_ 'self' as defined by A.__init__()  Why?

Because you're just re-binding the local variable name 'self' to refer
to a different object -- which has absolutely no effect on whatever
it was previously bound to.

This is always true, for whatever variable name, local or global.
Whatever 'x' is bound to, if you do
    x = anythingelse
now the name x is bound to whatever 'anythingelse' is, but this
has zilch effect on whatever the name x was previously bound to.

> Can I/Should I work around it?

You shouldn't (because of the principle of minimal astonishment),
but if you want to, you can get almost the same effect:

class B(A):
    def __init__(self):
        A.__init__(self)
        newbie = A.make(self)
        self.__dict__, self.__class__ = newbie.__dict__, newbie.__class__

A __dict__ and a __class__ essentially summarize everything
about a class-instance (here, the ones 'self' and 'newbie' refer
to).  The tiny exception is in the (almost-methaphysical...)
"identity" itself (builtin function id).


Alex






More information about the Python-list mailing list