Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 'cls' and 'self' 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      @classmethod     def from_fullname(cls, fullname):         cls.firstname, cls.lastname = fullname.split(' ', 1) 
like image 967
Scaraffe Avatar asked Jan 06 '11 08:01

Scaraffe


People also ask

What is difference between self and CLS in Python?

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.

What does CLS in Python mean?

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).

What do self and CLS refer to?

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.

What is the difference between self and __ init __ methods in Python class?

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.


1 Answers

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.

like image 178
Baskaya Avatar answered Oct 18 '22 19:10

Baskaya