16

Is it possible for static method of a class to return a new instance of its class.

class Foo(object):
    @staticmethod
    def return_new():
        "returns a new instance of the class"
        new_instance = ???
        return new_instance

I want it so any subclass of Foo will return the subclass rather than a Foo instance. So replacing ??? with Foo() will not do.

4

1 回答 1

20

Why don't you use classmethod? Using classmethod, the method receives the class as the first parameter (cls in the following example).

class Foo(object):
    @classmethod
    def return_new(cls):
        "returns a new instance of the class"
        new_instance = cls()
        return new_instance

class Bar(Foo):
    pass

assert isinstance(Foo.return_new(), Foo)
assert isinstance(Bar.return_new(), Bar)
于 2013-11-05T15:09:00.717 回答