class – Difference between cls and self in Python classes?

class – Difference between cls and self in Python classes?

The distinction between self and cls is defined in PEP 8 . As Adrien said, this is not mandatory. Its 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.

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.

class – Difference between cls and self in Python classes?

Its used in case of a class method. Check this reference for further details.

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

Leave a Reply

Your email address will not be published. Required fields are marked *