Why is ‘cls’ used instead of ‘self’?
Any help appreciated
The distinction between
"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:
selffor the first argument to instance methods.
clsfor the first argument to class methods.
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
self are used (PEP8).
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 .