Overwriting 'self' in constructor?

Costas Malamas costas at malamas.com
Tue Oct 10 13:17:32 EDT 2000


Thanks for the input, but I was aiming for something else:

> 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.
    So, could I copy the structure of another object onto it somehow?


> 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?
    Unfortunately, no; for my own reasons, I want to change the behavior of
class A, so as to make the two step process an one-step deal.  I don't mind even
if I didn't extend A but I basically want to do this:
z = B(), not z = F.make(B)

I guess I am being pedantic here...

Thanks again,

Costas






More information about the Python-list mailing list