Static methods and class methods in Python

Coding with Python

🕑 This lesson will take about 20 minutes

In object-oriented programming (OOP), static methods and class methods are special kinds of methods that are associated with a class rather than with an object (an instance of the class).

Static methods

Static methods are methods that are bound to a class rather than an object instantiated from the class. This means that static methods can be called on the class itself, without the need to create an instance of the class (an object). Static methods are used to perform functionality that does not depend on the state of any object. In Python, you can define a static method using the @staticmethod decorator.

In the example below, a static method called my_static_method() is created inside a class called MyClass. Note the use of the @staticmethod decorator at the top of the static method. Note there does not need to be an object created from the class for the static model to be called, however, when the method is called, it must be called on the class itself. For example: MyClass.my_static_method()

Class methods

Class methods are also bound to a class itself but can access or modify class state (class variables/attributes). They are passed a reference to the class as the first argument, conventionally named cls. Class methods are defined using the @classmethod decorator in Python.

The main difference between static and class methods is that class methods can access and modify the class state (class variables), whereas static methods cannot access and modify class state and are often used for more general utility functions.

In the example below, there is a class called MyClass. In this class, there is a class variable called class_variable (with an initial string value of "original class variable value", and there are two class methods - one called get_class_variable() and one called change_class_variable() .

  • The get_class_variable() method gets one of the MyClass class variable’s values (from the class, not an object) and returns it.

  • The change_class_variable() method is used to modify the class variable from the MyClass class by giving it a new specified value.

In the example code, when these methods are called we can see the original class variable value, and its new value after it has been changed. Remember, the class methods are accessing and/or modifying a class state, not an object state.

The output this program produces will be:

original class variable value

new class variable value

In the next lesson, we will look at how to override methods.

Next lesson: Overriding methods