Python
cls
self
Python classes
OOP

Difference between 'cls' and 'self' in Python classes?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python classes, self and cls both refer to context, but they point to different objects. self refers to an instance, while cls refers to the class itself. Knowing when to use each one is essential for clean object-oriented code, especially when building reusable APIs and alternative constructors.

self in Instance Methods

Instance methods operate on one object at a time. The first parameter is conventionally named self and gives access to instance attributes and other instance methods.

python
1class Counter:
2    def __init__(self, start=0):
3        self.value = start
4
5    def increment(self, amount=1):
6        self.value += amount
7        return self.value
8
9
10c1 = Counter()
11c2 = Counter(10)
12print(c1.increment())
13print(c2.increment(5))

Each object has its own state, so self.value for one instance does not affect another.

cls in Class Methods

Class methods are declared with @classmethod. Their first parameter is conventionally named cls, representing the class object.

python
1class User:
2    domain = "example.com"
3
4    def __init__(self, username):
5        self.username = username
6
7    @classmethod
8    def from_email(cls, email):
9        username = email.split("@")[0]
10        return cls(username)
11
12
13u = User.from_email("[email protected]")
14print(type(u).__name__, u.username)

cls makes the method aware of inheritance and supports returning instances of subclasses automatically.

Why cls Helps with Inheritance

Alternative constructors written as class methods are subclass-friendly. They return the subclass type when called from that subclass.

python
1class Event:
2    def __init__(self, name):
3        self.name = name
4
5    @classmethod
6    def from_slug(cls, slug):
7        return cls(slug.replace("-", " ").title())
8
9
10class Webinar(Event):
11    pass
12
13w = Webinar.from_slug("advanced-python-patterns")
14print(type(w).__name__, w.name)

If this method used the base class name directly, subclass behavior would break.

Static Methods and Context-Free Logic

@staticmethod methods receive neither self nor cls. Use them when logic belongs conceptually to the class namespace but does not need instance or class state.

python
1class MathTools:
2    @staticmethod
3    def is_even(number):
4        return number % 2 == 0
5
6print(MathTools.is_even(8))

Choosing static, class, or instance methods correctly communicates intent.

Common Design Patterns

Common uses of instance methods include mutating object state and validating per-object fields.

Common uses of class methods include parsing input into instances, loading objects from dictionaries, and creating predefined variants.

Use class attributes through cls when the value should be shared across all instances. Use instance attributes through self when each object should track its own value.

Quick Decision Guide for Method Type

A practical rule set can reduce design confusion when adding methods to classes. Use an instance method when logic needs object-specific data. Use a class method when logic needs class-level configuration or should return class instances. Use a static method when logic is related conceptually but independent of object or class state.

python
1class Parser:
2    default_sep = ","
3
4    def __init__(self, sep=None):
5        self.sep = sep or self.default_sep
6
7    def split(self, text):
8        return text.split(self.sep)
9
10    @classmethod
11    def with_tab_separator(cls):
12        return cls(sep="	")
13
14    @staticmethod
15    def normalize(text):
16        return text.strip().lower()

This separation improves readability and makes class APIs easier to maintain as features grow.

Common Pitfalls

A frequent mistake is trying to access instance-only data from a class method. Class methods do not have a specific object unless you create one.

Another issue is using hard-coded class names inside alternative constructors. That prevents proper subclass return types.

Developers also confuse mutable class attributes with instance attributes. Shared mutable class data can leak changes across instances unexpectedly.

A final pitfall is renaming self or cls to unusual names. Python allows it, but readability suffers and team code becomes inconsistent.

Summary

  • self refers to a specific instance in instance methods.
  • cls refers to the class object in class methods.
  • Class methods are ideal for alternative constructors and inheritance-friendly factories.
  • Static methods are for logic that needs no instance or class state.
  • Choose method type by ownership of data and expected call semantics.

Course illustration
Course illustration

All Rights Reserved.