Why is cls
sometimes used instead of self
as an argument in Python classes?
For example:
class Person: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname @classmethod def from_fullname(cls, fullname): cls.firstname, cls.lastname = fullname.split(' ', 1)
The difference between the keywords self and cls reside only in the method type. If the created method is an instance method then the reserved word self has to be used, but if the method is a class method then the keyword cls must be used.
cls accepts the class Person as a parameter rather than Person's object/instance. Now, we pass the method Person. printAge as an argument to the function classmethod . This converts the method to a class method so that it accepts the first parameter as a class (i.e. Person).
In conclusion, 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.
The self in keyword in Python is used to all the instances in a class. By using the self keyword, one can easily access all the instances defined within a class, including its methods and attributes. __init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor.
The distinction between "self"
and "cls"
is defined in PEP 8
. As Adrien said, this is not 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With