Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)
recategorized by

I want to know why is cls sometimes used rather than 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)

1 Answer

0 votes
by (107k points)
edited by

The difference between the "self" and "cls" is defined in PEP 8 in Python. Please be informed that this is not necessary to always mention the cls. It's a coding style. PEP 8 says:

Function and method arguments:

You need to always work with the self for the first argument to instance methods. And you need to use cls for the first argument to class methods.

Do check out the below Python tutorial video:

31k questions

32.9k answers

507 comments

693 users

...