Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #108416

Re: A problem with classes - derived type

From Yann Kaiser <kaiser.yann@gmail.com>
Newsgroups comp.lang.python
Subject Re: A problem with classes - derived type
Date 2016-05-09 06:51 +0000
Message-ID <mailman.542.1462776725.32212.python-list@python.org> (permalink)
References <ngp370$eu6$1@gioia.aioe.org> <CANUJvPV8S7Svj7=joXGHXAOFHTP4N2RxyW3R-ZMqhUjZ66TGTQ@mail.gmail.com>

Show all headers | View raw


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@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@gmail.com
yann.kaiser@efrei.net
+33 6 51 64 01 89
https://github.com/epsy

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

A problem with classes - derived type Paulo da Silva <p_s_d_a_s_i_l_v_a_ns@netcabo.pt> - 2016-05-09 05:20 +0100
  Re: A problem with classes - derived type Yann Kaiser <kaiser.yann@gmail.com> - 2016-05-09 06:51 +0000
  Re: A problem with classes - derived type Peter Otten <__peter__@web.de> - 2016-05-09 08:59 +0200
  Re: A problem with classes - derived type Paulo da Silva <p_s_d_a_s_i_l_v_a_ns@netcabo.pt> - 2016-05-09 19:59 +0100

csiph-web