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


Groups > comp.lang.python > #83766

Re: Calling a derived class's constructor from a parent method

References <cb109c66-090a-4779-b00e-43d964ae7252@googlegroups.com>
Date 2015-01-15 03:56 +1100
Subject Re: Calling a derived class's constructor from a parent method
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.17728.1421255034.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Jan 15, 2015 at 3:45 AM, jason <jasonsewall@gmail.com> 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.

Assuming you require that every subclass be able to be constructed
with that single parameter, it's not too hard. You get a 'self'
parameter; its type is the type you want to construct.

    def foo(self, s):
        return type(self)(s)

That should work just fine on either 2.7 or 3.x.

I'm not sure what this function would do in context, but this basic
technique should work.

ChrisA

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


Thread

Calling a derived class's constructor from a parent method jason <jasonsewall@gmail.com> - 2015-01-14 08:45 -0800
  Re: Calling a derived class's constructor from a parent method Ian Kelly <ian.g.kelly@gmail.com> - 2015-01-14 10:00 -0700
  Re: Calling a derived class's constructor from a parent method Chris Angelico <rosuav@gmail.com> - 2015-01-15 03:56 +1100
  Re: Calling a derived class's constructor from a parent method Mark Lawrence <breamoreboy@yahoo.co.uk> - 2015-01-14 17:05 +0000
    Re: Calling a derived class's constructor from a parent method jason <jasonsewall@gmail.com> - 2015-01-14 10:10 -0800
      Re: Calling a derived class's constructor from a parent method Dave Angel <davea@davea.name> - 2015-01-14 13:41 -0500
    Re: Calling a derived class's constructor from a parent method alister <alister.nospam.ware@ntlworld.com> - 2015-01-14 18:18 +0000
  Re: Calling a derived class's constructor from a parent method Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-01-15 11:40 +1100
    Re: Calling a derived class's constructor from a parent method Mark Lawrence <breamoreboy@yahoo.co.uk> - 2015-01-15 04:44 +0000

csiph-web