Understanding Python Class Method with Examples

The Python class method is an invaluable concept every budding programmer should grasp to elevate their coding skills. In the dynamic world of programming, understanding such methods can open doors to creating more efficient and organised code. Whether you’re just starting or looking to polish your existing skills, delving into Python class methods is a fantastic way to improve. Curious to learn more? Keep reading as we explore this fundamental aspect and its real-world applications.

What is a Class Method in Python?

A class method in Python is a method that is tied to the class rather than its instances. This means it can access and modify class-level data but cannot access instance-specific data unless passed explicitly.

Class methods are commonly used for:

  • Creating factory methods that return class objects
  • Working with class-level variables
  • Performing operations that apply to the class as a whole

To define a class method, you use the built-in @classmethod decorator. This tells Python to pass the class itself as the first argument to the method, instead of the instance.

The first parameter of a class method is conventionally named cls, which refers to the class — similar to how self refers to the instance in instance methods.

Syntax of Python Class Method

Here’s the basic syntax for creating and using a class method:

class ClassName:
    
    class_variable = "Shared value"
    
    @classmethod
    def method_name(cls, additional_parameters):
        # Method body
        # Access or modify class_variable using cls
        print(cls.class_variable)

Key Points:

  • @classmethod must be placed above the method definition.
  • The first parameter must be cls.
  • You call a class method using the class name: ClassName.method_name().

Example of a Python Class Method

Let’s look at a real-world example that demonstrates how class methods work.

class Employee:
    company_name = "Techaroha"

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

    @classmethod
    def change_company(cls, new_name):
        cls.company_name = new_name

    def show_details(self):
        print(f"Name: {self.name}, Salary: {self.salary}, Company: {self.company_name}")

Line-by-Line Breakdown:

  • company_name = "Techaroha": A class variable shared by all instances.
  • __init__: Standard constructor to set name and salary for each object.
  • @classmethod def change_company(cls, new_name): A class method to modify the class variable company_name.
  • show_details(): Displays the employee details including the current company name.

Using the Class and Class Method

# Create two employee instances
emp1 = Employee("Alice", 50000)
emp2 = Employee("Bob", 60000)

# Show initial details
emp1.show_details()
emp2.show_details()

# Change the company name using class method
Employee.change_company("CodeMatrix")

# Show updated details
emp1.show_details()
emp2.show_details()

🖨️ Output:

Name: Alice, Salary: 50000, Company: Techaroha
Name: Bob, Salary: 60000, Company: Techaroha
Name: Alice, Salary: 50000, Company: CodeMatrix
Name: Bob, Salary: 60000, Company: CodeMatrix

As you can see, the class method successfully updates the shared company_name for all instances.

Difference Between Class Method, Static Method, and Instance Method

FeatureInstance MethodClass MethodStatic Method
DecoratorNo decorator@classmethod@staticmethod
First Argumentself (refers to the instance)cls (refers to the class)No special first argument
Access Instance DataYesNoNo
Access Class DataYesYesNo (unless accessed explicitly)
Can Modify Class StateNoYesNo
Bound ToInstanceClassClass
How to Callobj.method()Class.method() or obj.method()Class.method() or obj.method()

When to Use Each Method

Instance Method

Use when:

  • You need to access or modify object-specific data.
  • Behavior depends on the state of the specific object.

Example use case: A method that calculates an employee’s yearly bonus based on their salary.

Class Method

Use when:

  • You need to access or modify class-level data shared across all instances.
  • You’re writing factory methods that return class objects using different inputs.

Example use case: Changing a shared configuration or creating new objects with alternative constructors.

Static Method

Use when:

  • The method performs a utility task that doesn’t need class or instance data.
  • You want a function to logically belong to the class but it doesn’t need access to the class or instance itself.

Example use case: Calculating a tax rate or formatting a string.

Use Cases of Class Methods

Class methods are especially useful when dealing with operations that affect the class as a whole rather than individual instances. Below are common scenarios where class methods are the best fit:

1. Factory Methods

Class methods are often used to define factory methods — alternative constructors that return an instance of the class with specific parameters or logic.

Example:

class Date:
    def __init__(self, day, month, year):
        self.day = day
        self.month = month
        self.year = year

    @classmethod
    def from_string(cls, date_str):
        day, month, year = map(int, date_str.split('-'))
        return cls(day, month, year)

Usage:

date1 = Date.from_string("31-07-2025")

2. Tracking Object Creation

You can use class methods to keep count of how many instances have been created, by updating a class variable each time a new object is initialized.

Example:

class Product:
    count = 0

    def __init__(self, name):
        self.name = name
        Product.increment_count()

    @classmethod
    def increment_count(cls):
        cls.count += 1

3. Working with Class-Level Data

If you want to modify or access data that belongs to the class and is shared by all instances, class methods are the ideal tool.

Example:

class AppSettings:
    default_theme = "Light"

    @classmethod
    def change_theme(cls, new_theme):
        cls.default_theme = new_theme

Common Mistakes and Best Practices

1. Using self Instead of cls
Using self as the first parameter in a class method will cause errors or lead to unintended behavior, because the method expects to receive the class, not an instance.

Incorrect:

@classmethod
def set_value(self, value):  # Should be cls, not self
    cls.value = value

Correct:

@classmethod
def set_value(cls, value):
    cls.value = value

2. Forgetting the @classmethod Decorator
If you don’t use the decorator, Python will treat the method as a regular instance method, and cls won’t receive the class as expected.

Incorrect:

def set_value(cls, value):  # Missing @classmethod
    cls.value = value

Correct:

@classmethod
def set_value(cls, value):
    cls.value = value

Best Practices

  • Always use descriptive names for your class methods, especially for factory methods (e.g., from_string, with_defaults).
  • Keep the method logic related to class-level operations only.
  • Don’t use class methods when instance-specific behavior is required — use instance methods instead.
  • Use class methods for alternate constructors or when modifying shared state.

Discover our AI-powered python online compiler, where creativity meets technology. Instantly write, run, and test your code with the help of AI, making coding smoother and faster. Say goodbye to long setup times and hello to more productive programming sessions—right from your browse

Conclusion

Python class method unlocks powerful programming skills, enabling manipulation of class variables with ease. Mastering it imparts confidence, transforming coding from daunting to delightful. Ready to level up? Explore more programming languages like Java and C++ at Newtum. Dive in and see what you can create!

Edited and Compiled by

This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.

About The Author