A problem with classes - derived type

Yann Kaiser kaiser.yann at gmail.com
Mon May 9 02:51:53 EDT 2016


If you can't change A to use something like "type(self)(...)" to create its
return value, you could use the dark side and swap res's __class__:

    res.__class__ = B

Or:

    res.__class__ = type(self)

Do note that B.__init__ will not be run when you do this, so it is up to
you to execute any additional initialization B might require.

Alternatively if it makes sense for you you can call B's methods on an A
object like so:

    B.b_method(a_object, ...)

On Mon, 9 May 2016 at 06:26 Paulo da Silva <p_s_d_a_s_i_l_v_a_ns at netcabo.pt>
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?
>
> Thanks.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
Yann Kaiser
kaiser.yann at gmail.com
yann.kaiser at efrei.net
+33 6 51 64 01 89
https://github.com/epsy



More information about the Python-list mailing list