← Back to list

Learning about classmethod in Python

In Python, classes serve as blueprints for objects. Within these classes, methods are often defined using self, which refers to the…

Jesús · 2024-11-30 14:53 · 26 claps · 2.4 min read paywalled
#python #class-method #cl #python-programming #poo
Open on Medium ↗
Wiki topics: CRY · Crypto & Web3 EDU · Education & Learning 💻 · Programming

Learning about classmethod in Python

In Python, classes serve as blueprints for objects. Within these classes, methods are often defined using self, which refers to the instance of the class. But what if you need to work with the class itself rather than an instance?

This is where the classmethod decorator comes into play together with cls.

This story will walk you through what @classmethod does, why using cls is advantageous, and provide a practical use case to clarify its utility. By the end, you’ll be equipped to leverage @classmethod to write more efficient and maintainable code.

What is @classmethod?

In Python, methods are typically categorized as:

  • Instance methods (use self): Operate on individual instances of a class.
  • Class methods (use cls): Operate on the class itself, not on any specific instance.
  • Static methods: Independent of both instances and classes, acting like regular functions inside a class.

The @classmethod decorator transforms a method into a class method. Instead of the usual self, it takes cls as its first parameter, representing the class. With cls, you gain direct access to class attributes, methods, and constructors.

Why use cls over self?

Here’s a quick comparison:

Using cls provides:

  1. Flexibility: Easily create factory methods or alternate constructors.
  2. Maintainability: Allows updates to class-level attributes without hardcoding values.

Use Case: Creating Alternate Constructors

Imagine you’re designing a Product class for an e-commerce platform. You want to create Product instances from raw data but also provide a way to initialize them using JSON. Here’s how @classmethod and cls can be used:

class Product:
    # Class attribute
    currency = "USD"

    def __init__(self, name, price):
        self.name = name
        self.price = price

    @classmethod
    def from_json(cls, json_data):
        """Alternate constructor to create Product from JSON."""
        name = json_data["name"]
        price = json_data["price"]
        return cls(name, price)  # Uses cls to create a new instance

    @classmethod
    def set_currency(cls, currency_code):
        """Modify the default currency for all products."""
        cls.currency = currency_code

# Example usage
data = {"name": "Laptop", "price": 999.99}
product = Product.from_json(data)
print(product.name)  # Output: Laptop

# Update the class-level currency
Product.set_currency("EUR")
print(Product.currency)  # Output: EUR

Breaking It Down

  1. The from_json Method
  • Acts as a factory method.
  • Uses cls to dynamically create instances. If the Product class is subclassed, cls ensures the correct class type is used.
  1. The set_currency Method
  • Modifies a class-level attribute (currency), affecting all instances of the class.

Advantages of cls in @classmethod

  • Dynamic Behavior: When using cls, the method is bound to the class, making it easy to work with derived classes.
  • Encapsulation: Avoids hardcoding the class name. Changes to the class structure propagate seamlessly.
  • Readability and Maintenance: Clearly conveys that the method is class-specific, reducing confusion in complex codebases.

Conclusion

The @classmethod decorator and its use of cls provide a powerful way to enhance class-level functionality in Python. By focusing on the class itself rather than individual instances, you can create flexible solutions like alternate constructors and centralized class-wide behavior.

In simple words, it allows us to modify the class, and not individual instances.

Thank you very much for your attention!

[embed]List of all my stories In this story I will compile all my stories categorized, to make it easier to find a story that interests the reader.medium.com


메타데이터
post_id
8161bcdf3673
slug
learning-about-classmethod-in-python-8161bcdf3673
url
https://medium.com/@jdgb.projects/learning-about-classmethod-in-python-8161bcdf3673
canonical_url
https://medium.com/@jdgb.projects/learning-about-classmethod-in-python-8161bcdf3673
author_url
https://medium.com/@jdgb.projects
status
ok
fetched_at
2026-08-17 05:24:26