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


Groups > comp.lang.python > #108417

Re: A problem with classes - derived type

From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: A problem with classes - derived type
Date 2016-05-09 08:59 +0200
Organization None
Message-ID <mailman.543.1462777389.32212.python-list@python.org> (permalink)
References <ngp370$eu6$1@gioia.aioe.org> <ngpcgb$f20$1@ger.gmane.org>

Show all headers | View raw


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.

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