Home » Python » What is the 'cls' variable used in python classes?

What is the 'cls' variable used in python classes?

Posted by: admin November 1, 2017 Leave a comment

Questions:

Why is ‘cls’ used instead of ‘self’?
Any help appreciated

Answers:

The distinction between "self" and "cls" is defined in PEP 8 . As Adrien said, this is not a mandatory. It’s a coding style. PEP 8 says:

Function and method arguments:

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

Questions:
Answers:

It’s used in case of a class method. Check this reference for further details.

EDIT: As clarified by Adrien, it’s a convention. You can actually use anything but cls and self are used (PEP8).

Questions:
Answers:

This is very good question but not as wanting as question.
There is difference between ‘self’ and ‘cls’ used method though analogically they are at same place

def moon(self,moon_name):
    self.MName =moon_name
    
#but here cls method its use is different 


def moon(cls,moon_name):
    instance=cls()
    instance.MName=moon_name

Now you can see both are moon function but one can be used inside class while other function name moon can be used for any class.

For practical programming approach :

While designing circle class we use area method as cls instead of self because we don’t want area to be limited to particular class of circle only .