Calling a derived class's constructor from a parent method

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jan 14 19:40:43 EST 2015


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)

A.foo is broken, or at least rude.  Change it to this:

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



> class B(A):
>       def __init__(self, s):
>             A.__init__(self, s)

Unrelated:

It is better to call super than manually call the superclass. Calling A
directly means your class is no longer compatible with multiple
inheritance.

    def __init__(self, s):
        super(B, self).__init__(s)


> I'm using Python 2.7.5, but I'm curious what the 3.x answer is too.


The answer in 3.x is the same, except that super() can auto-detect the right
arguments:

        super().__init__(s)



-- 
Steven




More information about the Python-list mailing list