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
@staticmethoddecorator makes it a static method. -
Consider the following two examples:
-
Example1defines the methodsquare, outside the class definition ofCircle, and uses it inside the classCircle. -
Example2defines 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,
squarefunction 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
squarefunction 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, thesquaremethod is defined inside the classCircleand decorated withstaticmethod. -
Then it is accessed as
self.square. -
You can also observe that
squaremethod 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
- Question 1: Class and Static Methods - 1 - Hands On
- Question 2: Class and Static Methods - 2 - Hands On
- Question 3: Class and Static Methods - 3 - Hands On
- Question 4: What is an instance method in OOP, and how does it differ from a static method?
- Question 5: Why would you choose to use a static method over an instance method in OOP?