A problem with classes - derived type

Peter Otten __peter__ at web.de
Mon May 9 02:59:20 EDT 2016


Paulo da Silva wrote:

> Hi!
> 
> Suppose I have a class A whose implementation I don't know about.
> That class A has a method f that returns a A object.
> 
> class A:
> ...
> def f(self, <...>):
> ...
> 
> Now I want to write B derived from A with method f1. I want f1 to return
> a B object:
> 
> class B(A):
> ...
> def f1(self, <...>):
> ...
> res=f(<...>)
> 
> How do I return res as a B object?

In the general case you need enough knowledge about A to create a B instance 
from an A instance:

class B(A):
    @classmethod
    def from_A(cls, a):
        b = cls(...) # or B(...)
        return b
    def f1(self, ...):
        return self.from_A(self.f(...))

If the internal state doesn't change between A and B, and A is written in 
Python changing the class of the A instance to B

class B(A):
    def f1(...):
        a = self.f(...)
        a.__class__ = B
        return a

may also work.




More information about the Python-list mailing list