Summary: In this tutorial, we will uncover the difference between self and cls in the Python programming language.

self

self in Python holds the reference of the current working instance. This reference is passed as the first argument to every instance methods of the class by Python itself.

class MyClass:
    def what_is_self(self):
        print(self)
        
MyClass().what_is_self()  #outputs <__main__.MyClass object at 0x7fef4c820d00>

cls

cls in Python holds the reference of the class. It is passed as the first argument to every class methods (methods with @classmethod decorator) by Python itself.

class MyClass:
    @classmethod
    def what_is_cls(cls):
        print(cls)
        
MyClass().what_is_cls()  #outputs <class '__main__.MyClass'>

It is important to note that self and cls are not reserved keywords. They are just naming conventions in Python.

It means we can rename them to whatever we want, the underlying significance will remain the same.

self vs cls

Since self refers to the instance and cls refers to the class, they differ in terms of scope and accessibilty.

selfcls
self holds the reference of the current working instance.cls holds the reference of the current working class.
self also holds the reference of the class as self.__class__cls doesn’t hold any reference to any instances of the class.
self has access to both instance and class data members of the current working instance.Using cls we can access only the class data members of the current class.
Variables initialized using self get declared in the instance’s scope.Variable initialized using cls get declared in the class’s scope.

Here are some examples that shows the difference between self and cls in Python.

Difference 1: cls cannot access instance data members

class MyClass:
    #class variable
    cvar = "class variable"
    
    def __init__(self):
        #instance variable
        self.ivar = "intance variable"
    
    @classmethod
    def display_using_cls(cls):
        print(cls.cvar)
        #print(cls.ivar)  #raises AttributeError
    
    #instance method
    def display_using_self(self):
        print(self.cvar)
        print(self.ivar)
        
obj = MyClass()
obj.display_using_cls()
obj.display_using_self()

Difference 2: self contains cls, whereas vice versa is not True

class MyClass:
    #instance method    
    def self_contains_cls(self):
        print(self.__class__)   #outputs <class '__main__.MyClass'>
        
obj = MyClass()
obj.self_contains_cls()

In conclusion, self refers to the current working instance and is passed as the first argument to all the instance methods whereas cls refers to the class and is passed as the first argument to all the class methods.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply