overriding method that returns base class object
Scott David Daniels
Scott.Daniels at Acm.Org
Mon Feb 16 19:23:43 EST 2004
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
...
Hope this helps
-Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list