Summary: In this tutorial, we will uncover the difference between self and cls in the Python programming language.
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 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
clsare 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
self refers to the instance and
cls refers to the class, they differ in terms of scope and accessibilty.
|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 ||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 |
|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
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()
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.