What do @classmethod and @staticmethod mean in Python, and how are they different?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Unlocking the Power of @classmethod and @staticmethod in Python

Ever tried organizing your toolbox and realized that having the right tools in the right place makes all the difference? Similarly, in Python, @classmethod and @staticmethod are like specialized tools that help you build cleaner and more efficient classes. Let’s dive into what these decorators mean and how they can transform your Python coding experience!

What Are @classmethod and @staticmethod

@classmethod

A @classmethod is a method that belongs to the class itself rather than any particular instance of the class. It receives the class as its first argument, typically named cls, allowing it to access and modify class state that applies across all instances.

Example:

class Book: total_books = 0 def __init__(self, title): self.title = title Book.total_books += 1 @classmethod def get_total_books(cls): return cls.total_books # Usage book1 = Book("Python 101") book2 = Book("Data Science with Python") print(Book.get_total_books()) # Output: 2

In this example, get_total_books is a class method that accesses the total_books class variable, keeping track of how many Book instances have been created.

@staticmethod

A @staticmethod is a method that belongs to a class but does not access or modify the class or instance it belongs to. It behaves like a regular function but resides within the class's namespace, providing utility functions related to the class.

Example:

class MathUtility: @staticmethod def add(a, b): return a + b # Usage result = MathUtility.add(5, 3) print(result) # Output: 8

Here, add is a static method that simply adds two numbers. It doesn’t interact with any class or instance variables, making it a neat utility function within the MathUtility class.

Key Differences Between @classmethod and @staticmethod

Access to Class and Instance

  • @classmethod: Has access to the class (cls) and can modify class state that applies across all instances.
  • @staticmethod: Does not have access to the class (cls) or instance (self). It cannot modify class or instance state.

Use Cases

  • @classmethod: Ideal for factory methods, alternative constructors, or methods that need to access or modify class-level data.

    Example:

    class Person: species = "Human" def __init__(self, name): self.name = name @classmethod def change_species(cls, new_species): cls.species = new_species # Usage Person.change_species("Homo sapiens") print(Person.species) # Output: Homo sapiens
  • @staticmethod: Best for utility functions that perform tasks related to the class but don’t need to access class or instance data.

    Example:

    class TemperatureConverter: @staticmethod def celsius_to_fahrenheit(celsius): return (celsius * 9/5) + 32 # Usage temp_f = TemperatureConverter.celsius_to_fahrenheit(25) print(temp_f) # Output: 77.0

Practical Examples

Using @classmethod for Alternative Constructors

class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day @classmethod def from_string(cls, date_str): year, month, day = map(int, date_str.split('-')) return cls(year, month, day) # Usage date = Date.from_string("2024-04-27") print(date.year, date.month, date.day) # Output: 2024 4 27

Using @staticmethod for Utility Functions

class Validator: @staticmethod def is_valid_email(email): return "@" in email and "." in email # Usage print(Validator.is_valid_email("test@example.com")) # Output: True print(Validator.is_valid_email("testexample.com")) # Output: False

Additional Resources

Enhance your Python expertise and ace your interviews with these DesignGurus.io courses:

  • Grokking the Object Oriented Design Interview here
  • Grokking the System Design Interview here
  • Grokking the Coding Interview: Patterns for Coding Questions here

Helpful Blogs

Dive deeper into Python and object-oriented principles by visiting DesignGurus.io's blog:

By mastering @classmethod and @staticmethod, you can write more organized, efficient, and maintainable Python code. Happy coding!

TAGS
Coding Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Is it hard to join Oracle?
What is the correct order to learn DSA?
How to excel in system design interview?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
Grokking Advanced Coding Patterns for Interviews
Master advanced coding patterns for interviews: Unlock the key to acing MAANG-level coding questions.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.