Class Method in Python

A class method in Python is a method that is bound to the class and not the instance of the class. It is defined using the @classmethod decorator and takes cls as its first parameter, which represents the class itself. This allows class methods to access and modify class-level attributes or methods, making them particularly useful for creating factory methods that return class instances from various data forms, such as dictionaries or text strings.

Overview

Class methods are a type of method that can be called on the class itself or on an instance of the class. They are defined using the @classmethod decorator and take cls as their first parameter. This allows them to access class-level attributes or methods, which apply across all instances of the class. Class methods are particularly useful for maintaining a clear separation of concerns within a class, making the code more maintainable and scalable.

Defining Class Methods

To define a class method, use the @classmethod decorator. The first parameter of a class method is cls, which refers to the class itself. This is different from instance methods, which take self as the first parameter and are called on an instance of the class. Static methods, on the other hand, are defined with the @staticmethod decorator and do not take self or cls as a parameter.

Example: Creating a Class Method

Below is an example of how to create a class method in Python. This example demonstrates a Task class with a class method task_from_dict that creates an instance of the class from a dictionary.

Listing 8.6 Creating a class method

class Task:
    def __init__(self, title, desc, urgency):
       self.title = title
       self.desc = desc
       self.urgency = urgency
       self._status = "created"

   @classmethod
   def task_from_dict(cls, task_dict):
       title = task_dict["title"]
       desc = task_dict["desc"]
       urgency = task_dict["urgency"]
       task_obj = cls(title, desc, urgency)
       return task_obj

In this example, the task_from_dict method takes a dictionary as input and extracts the title, desc, and urgency to create a new Task object.

Another Example: Creating a Class Method from Text

Another example of a class method is task_from_text, which creates a Task instance from a text string.

Listing 13.8 Creating a class for testing (task_class.py)

class Task:
   def __init__(self, title, urgency):
       self.title = title
       self.urgency = urgency

   @classmethod
   def task_from_text(cls, text_data):
       title, urgency_text = text_data.split(",")
       urgency = int(urgency_text)
       task = cls(title, urgency)
       return task

   @classmethod
   def task_from_dict(cls, task_data):
       title = task_data["title"]
       urgency = task_data["urgency"]
       task = cls(title, urgency)
       return task

In this listing, the task_from_text method splits a text string into title and urgency, converts the urgency to an integer, and then creates a Task object.

Example: Circle Class

The following example demonstrates the use of a class method in a Python class:

Listing 15.2 File circle_cm.py

'''circle_cm module: contains the Circle class.'''
class Circle:
    '''Circle class'''
    all_circles = []              #A
    pi = 3.14159
    def __init__(self, r=1):
        '''Create a Circle with the given radius'''
        self.radius = r
        self.__class__.all_circles.append(self)
    def area(self):
        '''determine the area of the Circle'''
        return self.__class__.pi * self.radius * self.radius
 
    @classmethod             #B
    def total_area(cls):              #C
        total = 0
        for c in cls.all_circles:          #D
            total = total + c.area()
        return total
 
import circle_cm
c1 = circle_cm.Circle(1)
c2 = circle_cm.Circle(2)
circle_cm.Circle.total_area()
 
15.70795

c2.radius = 3
circle_cm.Circle.total_area()

31.415899999999997
#A Variable containing list of all circles that have been created
#B @classmethod decorator
#C cls used instead of self
#D cls can used in place of Circle

Explanation

  • Class Attribute: The Circle class has a class attribute all_circles which is a list that stores all instances of the Circle class created. This attribute is shared across all instances.
  • Instance Method: The area method calculates the area of a circle instance using the class attribute pi.
  • Class Method: The total_area method is a class method, indicated by the @classmethod decorator. It uses the cls parameter to iterate over all instances stored in all_circles and calculates the total area of all circles.
  • Usage: The class method total_area can be called on the class itself (Circle.total_area()) to compute the total area of all circle instances created.

Conclusion

Class methods are a powerful feature in Python that allow for the creation of methods that operate on the class itself rather than on instances. They are particularly useful for creating factory methods and maintaining a clear separation of concerns within a class. By organizing class methods to address specific functionalities, developers can enhance the maintainability and scalability of their code.

| Book Title | Usage of class method | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|-----------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Python How-To](https://www.manning.com/books/python-how-to) | Discusses class methods as a way to create factory methods that return class instances from various data forms, such as dictionaries or text strings. [more](https://livebook.manning.com/book/python-how-to/chapter-8/100) | Explains the use of `@classmethod` and `cls` for accessing class-level attributes. [more](https://livebook.manning.com/book/python-how-to/chapter-8/100) | Connects class methods to the concept of factory methods and separation of concerns. [more](https://livebook.manning.com/book/python-how-to/chapter-8/100) | Provides examples like `task_from_dict` and `task_from_text` to demonstrate creating class instances from different data formats. [more](https://livebook.manning.com/book/python-how-to/chapter-8/106) | Highlights the use of class methods for maintainability and scalability in code. [more](https://livebook.manning.com/book/python-how-to/chapter-9/1) |
| [The Quick Python Book, Fourth Edition](https://www.manning.com/books/the-quick-python-book-fourth-edition) | Describes class methods as methods bound to the class, allowing them to be called on the class itself or an instance. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/77) | Details the difference between class methods and static methods, emphasizing the `cls` parameter. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/244) | Links class methods to class-level data operations, such as calculating total area of all instances. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/77) | Uses the `Circle` class example to show how class methods can operate on class-level data. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/77) | Demonstrates practical use in calculating total area of all circle instances, showing relevance to class as a whole. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-15/77) |

FAQ (Frequently asked questions)

What parameter does a class method take?

What is the benefit of organizing class methods by specific functionalities?

What are class methods used for in the context of factory methods?

What is an example of a class method that creates an instance from a dictionary?