Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: A problem with classes - derived type Date: Mon, 09 May 2016 08:59:20 +0200 Organization: None Lines: 45 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: news.uni-berlin.de mT8Jri+k1ELjhNa6eAh51g3ZjIubQgX0IqB0qXNqZB1Q== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.001 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'derived': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'res': 0.09; 'python': 0.10; 'def': 0.13; '@classmethod': 0.16; 'instance:': 0.16; 'paulo': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'received:t-ipconnect.de': 0.16; 'subject:type': 0.16; 'wrote:': 0.16; 'object.': 0.22; 'subject:problem': 0.22; 'suppose': 0.22; 'written': 0.24; 'header:User-Agent:1': 0.26; "doesn't": 0.26; 'header:X-Complaints-To:1': 0.26; 'about.': 0.29; 'work.': 0.30; 'class': 0.33; 'changing': 0.34; 'instance': 0.35; 'knowledge': 0.35; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'method': 0.37; 'received:org': 0.37; 'enough': 0.39; 'to:addr:python.org': 0.40; 'subject:with': 0.40; 'received:de': 0.40; 'between': 0.65; 'object:': 0.84 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: p57bd9728.dip0.t-ipconnect.de User-Agent: KNode/4.13.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.22 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Mailman-Original-Message-ID: X-Mailman-Original-References: Xref: csiph.com comp.lang.python:108417 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.