overriding method that returns base class object

John Roth newsgroups at jhrothjr.com
Mon Feb 16 21:55:00 EST 2004


"Stuart McGraw" <smcg4191 at frii.RemoveThisToReply.com> wrote in message
news:40315037$0$199$75868355 at news.frii.net...
> 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.

What's bogus about it? You can change the
class of an instance to be anything you want.
The only issue might be the slots; I'm not all
that familiar with what restrictions they might
impose.

Granted, there are relatively few cases
where changing the class of an instance on
the fly is actually better than the alternatives,
but this might be one of them.

John Roth

>
>
> "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