DEV Community

Cover image for The Difference between Static and Class methods in Python.
Sam Sonter
Sam Sonter

Posted on • Updated on

The Difference between Static and Class methods in Python.

Object-oriented programming is a programming paragdigm that relies on the concept of objects.
These objects can have properties and their methods.

They are three types of methods in python:

  • Instance method
  • Class method
  • Static method

Instance method is the most comman type of method used in python class. To call an instance method, you need to create an object of the class and with the help of that object you can access instance method.

On other hand, both class method and static method can be accessed directly by using class name i.e without creating object of class. Though you can also access these methods using object of a class.

Class and Static methods have some basic differences. Let's have a look over the difference between class and static method.

Class method

  1. A class method is a method which bounds to class rather than object or instance of the that class.

  2. Class methods can be created using @classmethod
    decorator.

  3. It takes first parameter as class or any variable name which points to the class itself.

  4. It can access and modify the state of the class, that will be applicable across overall classs and its instances.

class classExample:
    @classmethod
    def class_method(css, arg1, arg2, ...):
    # methody body
Enter fullscreen mode Exit fullscreen mode

EXAMPLE:

class classExample:
#create variable
    x = 2
    @classmethod
    def modify(cls):
    cls.X = 5
    print(cls.x)

print(classExample.x) #2
obj = classExample()
print(obj.x) #2
classExample.modify() #5
print(classExample.x) #5

print(obj.x) #5
obj.modify() #5


Enter fullscreen mode Exit fullscreen mode

As you can see, in the example an initial value of x is 2.

But when we modify the value x using class method i.e
modify(), its value changes to 5, which indicates that a classs mehtod can access and modify the state of class.

Static method

  1. Static method is similar to class method, which also bounds to a class rather than object of that class.

  2. Static method can be created using @static method decorator.

  3. It doesn't take any specific first parameter like as in class methods.

  4. It cant access and modify the state of the class

class staticExample:
    #create variable
    x = 2
    @staticmethod
    def modify():
        x = 5
        print(x)
staticExample.modify() 
print(staticExample.x)
obj = staticExample()

print(obj.x)
obj.modify
Enter fullscreen mode Exit fullscreen mode

Sam Sonter

Top comments (0)