overriding method that returns base class object
Stuart McGraw
smcg4191 at frii.RemoveThisToReply.com
Mon Feb 16 18:20:18 EST 2004
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. And to correct what I originally
posted, A is implented in python (but I still can't
change it for administrative reasons), but it's properties
are declared with "__slots__ = [...]" if that makes a
difference. This is all in Python 2.3.3.
"Peter Hansen" <peter at engcorp.com> wrote in message news:4031481B.90B31C73 at engcorp.com...
> Stuart McGraw wrote:
> >
> > I have a class A from a third party that I cannot change
> > and is implemented in C. I derive my own class B from A
> > and add a couple new methods and override a method. The
> > problem is that A has a method (call it A.f() ) that creates
> > and returns a new A object. I need B.f() to return a B
> > object derived from A.f(). What is the best way to make
> > that happen?
>
> If I understand this correctly, it has nothing to do with the
> fact that the parent class is implemented in C and you just
> need to know a little uncommon syntax:
>
> class A:
> def f(self):
> return A()
> se
> class B(A):
> def f(self):
> obj = A.f(self)
> # do whatever you want to obj here
> return obj
>
> The key is what you mean by "a B object derived from A.f()". If
> by derived you mean something to do with _inheritance_, then
> either you don't understand inheritance or you weren't clear what
> you wanted.
>
> If you just mean you want B's f() to do something special to the
> A object that A.f() returns, then the above code should let you
> do that properly...
>
> -Peter
More information about the Python-list
mailing list