- 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
Add to BookmarkIntroduction
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
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
Random Blogs
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- 15 Amazing Keyword Research Tools You Should Explore
- Types of Numbers in Python
- AI & Space Exploration – AI’s Role in Deep Space Missions and Planetary Research
- Big Data: The Future of Data-Driven Decision Making
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Exploratory Data Analysis On Iris Dataset
- The Ultimate Guide to Starting a Career in Computer Vision
- String Operations in Python
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
- Downlaod Youtube Video in Any Format Using Python Pytube Library
- Google’s Core Update in May 2020: What You Need to Know
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- Datasets for Natural Language Processing
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- 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