- Object-Oriented Programming (OOP) in Python
-
Overview
- Introduction to OOP in Python
- Classes and Objects
- Constructors (__init__) and Destructors
- Inheritance (Single, Multiple, Multilevel)
- Polymorphism and Method Overriding
- Encapsulation and Data Hiding
- Abstract Classes and Interfaces
- Static and Class Methods
- Magic/Dunder Methods (__str__, __repr__)
- Metaclasses in Python
- Method Resolution Order (MRO) in Python
Static and Class Methods
Introduction
Python provides two special types of methods: static methods and class methods. These methods allow us to define behaviors at the class level rather than the instance level.
In this tutorial, we will cover:
- What static methods and class methods are
- The
@staticmethod
and@classmethod
decorators - Differences between instance, static, and class methods
- Real-world examples of when to use static and class methods
1. Instance Methods vs. Static Methods vs. Class Methods
Feature | Instance Method | Class Method | Static Method |
---|---|---|---|
Requires self ? | Yes | No | No |
Requires cls ? | No | Yes | No |
Can access instance variables? | Yes | No | No |
Can modify class variables? | No | Yes | No |
Belongs to | Object | Class | Class |
2. Static Methods in Python (@staticmethod
)
A static method is a method that does not depend on instance or class variables. It is simply a function that belongs to a class but does not access or modify class or instance attributes.
Defining a Static Method
A static method is defined using the @staticmethod
decorator.
class MathOperations:
@staticmethod
def add(a, b):
return a + b
# Calling the static method
print(MathOperations.add(10, 20)) # Output: 30
Since add()
does not use self
or cls
, it is a static method.
When to Use Static Methods?
When a method performs a task independent of class or instance attributes
For utility functions (e.g., math operations, data conversions)
3. Class Methods in Python (@classmethod
)
A class method is a method that works on the class level and can access or modify class variables. It takes cls
as its first parameter instead of self
.
Defining a Class Method
A class method is defined using the @classmethod
decorator.
class Employee:
company = "Dynamic Duniya" # Class variable
@classmethod
def set_company(cls, new_name):
cls.company = new_name # Modifying class attribute
# Before modification
print(Employee.company) # Output: Dynamic Duniya
# Changing company name
Employee.set_company("Tech Innovators")
print(Employee.company) # Output: Tech Innovators
The class method set_company()
modifies the class variable company
.
When to Use Class Methods?
When you need to modify class attributes
For alternative constructors (creating objects in different ways)
4. Real-World Examples
Example 1: Static Method for Utility Function
class Temperature:
@staticmethod
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
print(Temperature.celsius_to_fahrenheit(25)) # Output: 77.0
The method converts temperature and does not use instance or class variables, making it a static method.
Example 2: Class Method for Alternative Constructor
Class methods can be used to create objects in multiple ways.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, student_str):
name, age = student_str.split("-")
return cls(name, int(age))
# Creating student object using a string
s1 = Student.from_string("Amit-21")
print(s1.name, s1.age) # Output: Amit 21
The from_string()
class method allows us to create a Student
object from a formatted string.
5. Summary
Static methods (@staticmethod
): Do not use self
or cls
, used for utility functions
Class methods (@classmethod
): Use cls
, modify class variables, useful for alternative constructors
Instance methods: Use self
, operate on individual objects
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- Grow your business with Facebook Marketing
- Mastering Python in 2025: A Complete Roadmap for Beginners
- Top 15 Recommended SEO Tools
- What is YII? and How to Install it?
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- Types of Numbers in Python
- Top 10 Knowledge for Machine Learning & Data Science Students
- What Is SEO and Why Is It Important?
- Data Analytics: The Power of Data-Driven Decision Making
- SQL Joins Explained: A Complete Guide with Examples
- Datasets for Natural Language Processing
- Important Mistakes to Avoid While Advertising on Facebook
- Career Guide: Natural Language Processing (NLP)
- Google’s Core Update in May 2020: What You Need to Know
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset