What is the 'cls' variable used for in Python classes?


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

    def from_fullname(cls, fullname):
        cls.firstname, cls.lastname = fullname.split(' ', 1)
2/1/2018 6:51:14 PM

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.

6/30/2016 4:23:19 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow