Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static method returning an instance of its class

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.

like image 693
Tonis F. Piip Avatar asked Nov 05 '13 15:11

Tonis F. Piip


People also ask

Can static method return class object?

yep, no this in static methods. Never.

What does static method return?

it is a method accessible from outside the class where it is defined (public), it is a static method (static), it does not return any result (return type is void), and.

Can I create an instance in static method?

Static methods can access the static variables and static methods directly. Static methods can't access instance methods and instance variables directly. They must use reference to object. And static method can't use this keyword as there is no instance for 'this' to refer to.

What does a static method return in Java?

In Java, a static method may use the keyword void as its return type, to indicate that it has no return value.


1 Answers

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)
like image 187
falsetru Avatar answered Oct 13 '22 23:10

falsetru