overriding method that returns base class object

Paul Rubin http
Mon Feb 16 22:16:36 EST 2004


"Stuart McGraw" <smcg4191 at frii.RemoveThisToReply.com> writes:
> 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.

Ugh!!

> Yes, I know this is bogus.  But I am not sure what I should be doing.

I think you have to make B into a container for an A.  Something like:

class B(A):
     def __init__(self, *args, **kwds):
       self.newprop = 99
       self.wrapped_A = A(*args, **kwds)
     def a(self):
       x = B()
       x.wrapped_A = A.a(self.wrapped_A)
       return     # I want x to be a B, i.e have b() and .newprop.
     def __getattr__(self, attr):
       # delegate all inherited operations to the wrapped A object
       return A.__getattr__(self.wrapped_A, attr)

You might also be able to do something crazy, like change A's metaclass
so that its __new__ operation can make a B under certain circumstances.



More information about the Python-list mailing list