Overwriting 'self' in constructor?

Michal Wallace sabren at manifestation.com
Tue Oct 10 12:14:00 EDT 2000


On Tue, 10 Oct 2000, Costas Malamas wrote:

> 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)

i think python will let you do that, it just just doesn't do what you
want it to. :)

> The product of this is _always_ 'self' as defined by A.__init__()  Why?
> Can I/Should I work around it?

Why it happens:

   Because even though self starts out as a reference to the object
you're working with, when you say self=ANYTHING it stops referencing
the first object and starts referencing something else. Python doesn't
look inside your method for anything that happens to be named "self",
it just looks at the original object. You can do anything you want TO
the object, but you can't replace it with another object altogether.

How to deal with it:

   Usually, when talking about a factory you should have at least 3
classes... "A", "B", and "Factory"...  Factory returns one or the
other.. Perhaps something like this:

class Factory:
    defaultClass = A
    def make(someClass=None):
        what = someClass or defaultClass
        return what()

>>> f = Factory()
>>> f.make(A)
<A instance...>

Is that what you want?

Cheers,

- Michal
------------------------------------------------------------------------
www.manifestation.com  www.sabren.com  www.linkwatcher.com  www.zike.net
------------------------------------------------------------------------





More information about the Python-list mailing list