overriding method that returns base class object

Stuart McGraw smcg4191 at frii.RemoveThisToReply.com
Mon Feb 16 22:32:02 EST 2004


"Scott David Daniels" <Scott.Daniels at Acm.Org> wrote in message news:40316850$1 at nntp0.pdx.net...
> Stuart McGraw wrote:
> 
> > Sorry, you are right, I wasn't clear.  I mean B inherits from
> > A.  Here is what I am trying to do...
> > 
> > Class A has a method A.a() that returns an A.  I want a 
> > identical class but with an additional property .newprop
> > and method .b()  And I want .a() to return a B, not an A.
> > 
> >   class B (A):
> >     def __init__(self, *args, **kwds):
> >       A.__init__(self, *args, **kwds)
> >       self.newprop = 99
> >     def a(self):
> >       x = A.a(self)    # x is an A
> >       x.__class__ = B
> >       return x    # I want x to be a B, i.e have b() and .newprop.
> >     def b(self):
> >       ...something...
> > 
> > Yes, I know this is bogus.  But I am not sure what 
> > I should be doing. 
> Typically, you might want to do something like:
> 
> class B(A):
>      ...
>      def a(self):
>          x = self.__class__.__new__(self.__class__,...)
>          # __new__ Usually gets no more args here, but
> 
>          x.__init__(...)
>          # And here is where we do the actual init

I don't think this will work.  A.a() returns an A, but one that
is initialized differently than an A() instance.  That is, A.a() 
does more that just __new__() and __init__() to it.  So if I 
do the above, I end up with a subtype (right word?) of an
A(), not an A.a().

Now I think that my B.a() must call A.a() and somehow
dynamically change the type of the object received?  As suggesed
above, I tried to change the class (x.__class__ = B) but that
just results in an exception 
TypeError: __class__ assignment: 'B' object layout differs from 'A'

Or maybe what I am trying to do is not possible in Python?




More information about the Python-list mailing list