Understanding Static Methods in Python: Definition and Examples
Table of Content:
Static Method
-
A method defined inside a class and not bound to either a class or an object is known as Static Method.
-
Decorating a method using
@staticmethod
decorator makes it a static method. -
Consider the following two examples:
-
Example1
defines the methodsquare
, outside the class definition ofCircle
, and uses it inside the classCircle
. -
Example2
defines the static methodsquare
, inside the classCircle
, and uses it.
-
Static Method - Example
Example 1
def square(x): return x**2 class Circle(object): def __init__(self, radius): self.__radius = radius def area(self): return 3.14*square(self.__radius) c1 = Circle(3.9) print(c1.area()) print(square(10))
Output
47.7594 100
Static Method - Example...
-
In Example 1,
square
function is defined outside the classCircle
. -
It determines square of a number,
x
. -
It can be used outside and also inside the class
Circle
. -
Though existing
square
function serves the purpose, it is not packaged properly and does not appear as integral part of classCircle
.
Static Method - Example...
Example 2
class Circle(object): def __init__(self, radius): self.__radius = radius @staticmethod def square(x): return x**2 def area(self): return 3.14*self.square(self.__radius) c1 = Circle(3.9) print(c1.area()) print(square(10)) # -> NameError
Output
47.7594 NameError: name 'square' is not defined
Static Method - Example...
Example 2...
-
In
Example 2
, thesquare
method is defined inside the classCircle
and decorated withstaticmethod
. -
Then it is accessed as
self.square
. -
You can also observe that
square
method is no longer accessible from outside the classCircle
. -
However, it is possible to access the static method using Class or the Object as shown below.
print(Circle.square(10)) # -> 100 print(c1.square(10)) # -> 100