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.
yep, no this in static methods. Never.
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.
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.
In Java, a static method may use the keyword void as its return type, to indicate that it has no return value.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With