Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (50.2k points)

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 (108k 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:

Browse Categories

...