Is it possible to have static methods in Python which I could call without initializing a class, like:
ClassName.static_method()
A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.
A static method doesn't have access to the class and instance variables because it does not receive an implicit first argument like self and cls . Therefore it cannot modify the state of the object or class. The class method can be called using ClassName. method_name() as well as by using an object of the class.
A static method in Java is a method that is part of a class rather than an instance of that class. Every instance of a class has access to the method. Static methods have access to class variables (static variables) without using the class's object (instance).
Yep, using the staticmethod decorator
class MyClass(object): @staticmethod def the_static_method(x): print(x) MyClass.the_static_method(2) # outputs 2
Note that some code might use the old method of defining a static method, using staticmethod
as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3)
class MyClass(object): def the_static_method(x): print(x) the_static_method = staticmethod(the_static_method) MyClass.the_static_method(2) # outputs 2
This is entirely identical to the first example (using @staticmethod
), just not using the nice decorator syntax
Finally, use staticmethod
sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.
The following is verbatim from the documentation::
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C: @staticmethod def f(arg1, arg2, ...): ...
The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.
It can be called either on the class (such as
C.f()
) or on an instance (such asC().f()
). The instance is ignored except for its class.Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see
classmethod()
.For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.
New in version 2.2.
Changed in version 2.4: Function decorator syntax added.
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