Calling a derived class's constructor from a parent method

Ian Kelly ian.g.kelly at gmail.com
Wed Jan 14 18:00:11 CET 2015


On Wed, Jan 14, 2015 at 9:45 AM, jason <jasonsewall at gmail.com> wrote:
> class A(object):
>       def __init__(self, s):
>             self.s = s
>       def foo(self, s):
>             return A(s)

Instead of explicitly naming the return class here, do this:

    return self.__class__(s)

Alternatively, since you never use self elsewhere in the method, it
may be cleaner to use a classmethod here:

    @classmethod
    def foo(cls, s):
        return cls(s)

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

The answer is the same in 3.x.



More information about the Python-list mailing list