Calling a derived class's constructor from a parent method

alister alister.nospam.ware at ntlworld.com
Wed Jan 14 19:18:26 CET 2015


On Wed, 14 Jan 2015 17:05:27 +0000, Mark Lawrence wrote:

> On 14/01/2015 16:45, jason wrote:
>> If I have a class hierarchy like so:
>>
>>
>> class A(object):
>>        def __init__(self, s):
>>              self.s = s
>>        def foo(self, s):
>>              return A(s)
>>
>> class B(A):
>>        def __init__(self, s):
>>              A.__init__(self, s)
>>
>> If I make a B:
>>
>> b = B(0)
>>
>> I'd like b.foo(1) to return an instance of B. Is there a way to do that
>> besides implementing a construct(self, s) for each part of the
>> hierarchy? I.e. is there a way for the base class to look at self and
>> find out what type to create?
>>
>> I'm using Python 2.7.5, but I'm curious what the 3.x answer is too.
>>
>>
> I'm confused, can you please explain what you're trying to achieve
> rather than how you're trying to achieve it and I'm sure that others
> will give better answers than I can :)

why not just make another b?
b2=B(1)



-- 
The computer should be doing the hard work.  That's what it's paid to do,
after all.
             -- Larry Wall in <199709012312.QAA08121 at wall.org>



More information about the Python-list mailing list