In this post, we will learn the Difference between ‘cls’ and ‘self’ in Python classes As they both are used for referring to the same class objects but both have different meanings and here we will get to know those differences.
cls Vs Self Keywords
Both of the keywords are used for referring to the same class objects so here we have given an example of code to execute where we can find how one is different from the other and get it done when we need to implement both of them.
Here the keyword self is used for referring to the instance of a class that is being accessed. or in other words, we can say it is used for referring to the instance variables and for instance methods of the class we are operating.
Whereas the other keyword cls is used for referring to the class itself here there is no involvement of instance required. So it is generally used inside the class method and those methods which are being defined using the ‘class method’ decorator for getting access to the class variables and methods.
An example of the same is given below to understand better.
class MyClass: class_variable = 0 def __init__( self, instance_variable): self.instance_variable = instance_variable def instance_method( self): print( self.instance_variable) @classmethod def class_method( cls): print( cls.class_variable)
In this example of code given above, we used ‘self. instance variable’ forgetting the access of the instance of the class whereas we used ‘cls’. class variable’ for getting access to the variables which are the class level.
And the ways to use this method we have called them as followed.
obj = MyClass(42) # creates an instance of the class obj.instance_method() # prints 42 MyClass.class_variable = 10 # modifies the class-level variable MyClass.class_method() # prints 10
Here point to keep in mind is we can also use some other name in place of these names but conventionally they are names that people use. Provided we need to change the descriptions where they’re described in library.
There is another thing to keep in mind here is we can use the self can be used for accessing both instance and class level both where as cls can only be used for referring the class level objects.
To learn more about the Difference between ‘cls’ and ‘self’ in Python classes visit the Click here to learn more.
To learn more about python solutions to different python problems and tutorials for the concepts we need to know to work on python programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & Python Client To A Linux/Ubuntu Server Which Is Running C?.