overriding method that returns base class object
Stuart McGraw
smcg4191 at frii.RemoveThisToReply.com
Tue Feb 17 01:11:02 EST 2004
"Paul Rubin" <http://phr.cx@NOSPAM.invalid> rote in message news:7xwu6mmm3v.fsf at ruckus.brouhaha.com...
> "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.
Ahhhh.... I did not know about delegation. I do now, thanks.
A minor disadvantage is that, because I also delegate __setattr__
all the instance variable have to be assigned in the form
self.__dict__['var'], rather than self.var (as I discovered the hard
way). Ugly, but I can live with it. Thanks again.
More information about the Python-list
mailing list