Difference Between Class Methods, Static Methods, and Instance Methods in Python

Learn about class methods, static methods, and instance methods in Python with simple examples and when to use them.

Picture of Nsikak Imoh, author of Macsika Blog
The text Difference Between Class Methods, Static Methods, and Instance Methods in Python written on a white background image
The text Difference Between Class Methods, Static Methods, and Instance Methods in Python written on a white background image

Table of Content

The concepts of class methods, static methods, and instance methods are part of the core concepts in object-oriented Python.

Static and class methods work hand-in-hand to enforce developer intent about class design.

Knowing their differences and how to use them makes you able to write object-oriented Python that communicates its intent more clearly and will be easier to maintain in the long run.

In this post, we will explain and compare class methods, static methods, and instance methods in Python with simple examples and when to use them.

What is an Instance Method in Python?

Instance methods are regular methods you will use most of the time in a class.

They take the parameter, self, as a mandatory parameter, which points to an instance of the class.

Through the self parameter, instance methods can freely access attributes and other methods on the same object.

This allows them to modify an object's state.

Not only can they modify the state of an object, but instance methods can also access the class itself through the self.__class__ attribute.

This means instance methods can also modify the state of a class.

Let's look at an example:

class Student:
	def __init__(self, first_name, last_name):
		self.first_name = first_name
		self.last_name = last_name
		self.middle_name = None

	def set_middle_name(self, name):
		self.middle_name = name

	def get_middle_name(self):
		return self.middle_name

s = Student('Nsikak', Imoh')
print(s.get_middle_name("Macsika"))
s.set_middle_name("Macsika")
print(s.get_middle_name("Macsika"))
Highlighted code sample.

An instance method's first parameter, self, is the instance of the class that calls it.

Therefore, it must be called by an instance of the class rather than the class itself.

When to Use Instance Methods in Python?

Instance methods are commonly used to modify an object or class attribute.

What is a Class Method in Python?

A class method in Python is a method that takes the class itself as the first parameter.

The first parameter is usually mandatory, and we use cls to represent it.

Living up to its name, a class method can be called by the class directly without needing to instantiate an instance to call the method.

It's very convenient to define a class method in Python classes. We can just add a built-in decorator @classmethod before the declaration of a method.

Let's look at an example:

class Student:
	def __init__(self, first_name, last_name):
		self.first_name = first_name
		self.last_name = last_name
		self.middle_name = None

	def set_middle_name(self, name):
		self.middle_name = name

	@classmethod # get_from_string is a class method
	def get_from_string(cls, name_string: str):
		first_name, last_name = name_string.split()
		return Student(first_name, last_name)

s = Student.get_from_string('Nsikak Imoh')
print(s.first_name) # Nsikak
print(s.last_name) # Imoh

# can't call instance method directly by class name
s2 = Student.set_middle_name('Macsika')

# TypeError: set_middle_name() missing 1 required positional argument: 'name'
Highlighted code sample.

As seen in the code snippet above, s2=Student.set_middle_name('Macsika') causes a TypeError.

Since set_middle_name() is not decorated by the @classmethod code decorator, it is treated as an instance method.

An instance method's first parameter, self, is the instance of the class that calls it. Therefore, it must be called by an instance of the class rather than the class itself.

However, by being decorated by the @classmethod code decorator, get_from_string() is a class method whose first parameter is the class itself, so it can be invoked by the class directly.

When to Use Class Methods in Python?

The class method gives us abilities to add more functionalities to a class.

Class methods are commonly used to define a factory method.

The factory design pattern is one of the popular software design patterns.

In the class Student example, we defined a factory called get_from_string which can ‘produce' a Student instance from a string input.

Therefore, the class method gives us the ability to define factory methods that give us the flexibility to produce Student instances in our own way.

Why is that?

Well, we know the built-in __init__method is a constructor of a class, but what if we need to create an instance differently?

In such cases, using an instance method as a factory becomes complicated to produce new instances, because when we use an instance method, we must have an instance at first.

class Student:
	def __init__(self, first_name, last_name):
		self.first_name = first_name
		self.last_name = last_name
		self.middle_name = None

	def set_middle_name(self, name):
		self.middle_name = name

	@classmethod # get_from_string is a class method
	def get_from_string(cls, name_string: str):
		first_name, last_name = name_string.split()
		return Student(first_name, last_name)

	@classmethod
    def get_from_json(cls, json_obj):
	    pass
    
    # return student
    @classmethod
    def get_from_excle(cls, excle_file):
	    pass
   
    @classmethod
    def get_from_audio_record(cls,audio):
	    pass
Highlighted code sample.

What is a Static Method in Python?

A static method is a method within a class that doesn't have parameters of the class or an instance of the class.

We can define a static method using the built-in decorator @staticmethod.

Let's look at an example:

class Student:
	def __init__(self, first_name, last_name):
		self.first_name = first_name
		self.last_name = last_name
		self.middle_name = None

	def set_middle_name(self, name):
		self.middle_name = name

	@classmethod # get_from_string is a class method
	def get_from_string(cls, name_string: str):
		first_name, last_name = name_string.split()
		return Student(first_name, last_name)

	@staticmethod
	def pass_grade(grade):
		return 70 <= grade <= 100

print(Student.pass_grade(50)) # False
print(Student.pass_grade(87)) # True
print(Student('Nsikak', 'Imoh').
pass_grade(100)) # True
Highlighted code sample.

As shown in the code snippet above, the accepted_grade is a static method, it doesn't have parameters like self or cls.

It doesn't matter whether we call a static method by class or instance.

When to Use Static Methods in Python?

Static methods can be used to manage classes and functions a lot better as helper or utility methods within a class.

You can find them in most of the popular open-source Python projects.

Since static methods do not contain parameters of a specific class or instances, we can define it as an independent function out of a class and use it as other normal functions out of classes.

For our example, the accepted_grade method checks whether a person's age is suitable to be a student, and this logic is closely related to the Student class.

Example of a Class with Class Methods, Static Methods, and Instance Methods in Python

Let's look at an example using all the different types of methods:

class Student:
	def __init__(self, first_name, last_name):
		self.first_name = first_name
		self.last_name = last_name

	def set_middle_name(self, name):
		self.middle_name = name

	@classmethod # get_from_string is a class method
	def get_from_string(cls, name_string: str):
		first_name, last_name = name_string.split()
		if Student.validate_name(first_name) and Student.validate_name(last_name):
			return cls(first_name, last_name)
		else:
			print('Invalid Names')
		return Student(first_name, last_name)

	@staticmethod
	def validate_name(name):
		return len(name) >= 100

nsikak = Student.get_from_string('Nsikak Imoh')
print(nsikak.first_name) # Nsikak
print(nsikak.last_name) # Imoh
Highlighted code sample.

Difference Between Class Methods, Static Methods, and Instance Methods

Here's the difference between class methods, static methods, and instance methods.

An instance method has a mandatory first parameter self which represents the instance itself. The instance method must be called by an instance of the class.

A class method has a mandatory first parameter cls which represents the class itself. A class method can be called by an instance or by the class directly. It is commonly used to define a factory method.

Lastly, a static method doesn't have any attributes of instances or the class. It can also be called by an instance or by the class directly.

Wrap Off

Instance methods need a class instance and can access the instance through self, class methods do not need a class instance, and they cannot access the instance self but they have access to the class itself via cls, while static methods do not have access to cls or self.

They work like regular functions but belong to the class's namespace.

If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.

Please share this post and for more insightful posts on business, technology, engineering, history, and marketing, subscribe to our newsletter.

Get the Complete Code of Python Code Snippets on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?