Why is cls
sometimes used instead of self
as an argument in Python classes?
For example:
class Person:
def __init__(sel
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.
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
@classmethod
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 .
cls
implies that method belongs to the class while self implies that the method is related to instance of the class,therefore member with cls
is accessed by class name where as the one with self is accessed by instance of the class...it is the same concept as static member
and non-static members
in java if you are from java background.
Instead of accepting a self parameter, class methods take a cls parameter that points to the class—and not the object instance—when the method is called. Since the class method only has access to this cls argument, it can’t modify object instance state. That would require access to self . However, class methods can still modify class state that applies across all instances of the class.
-Python Tricks
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).