Static Method in python

Rumman Ansari   Software Engineer   2022-11-24   500 Share
☰ Table of Contents

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 method square, outside the class definition of Circle, and uses it inside the class Circle.

    • Example2 defines the static method square, inside the class Circle, 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 class Circle.

  • 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 class Circle.

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, the square method is defined inside the class Circle and decorated with staticmethod.

  • Then it is accessed as self.square.

  • You can also observe that square method is no longer accessible from outside the class Circle.

  • 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