Difference between 'cls' and 'self' in Python classes?
Asked Answered
S

7

425

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)
Saturable answered 6/1, 2011 at 8:17 Comment(0)
F
425

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.

Factitive answered 25/1, 2011 at 15:27 Comment(1)
Can you please help suggest how the difference is "coding style" while abdilatiBashir answers the difference is of class-versus-instance? Do you disagree with him?Potpourri
K
137

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.

Kittie answered 11/3, 2018 at 14:55 Comment(2)
Thank you for the Java reference, now understand.Jokjakarta
Than you for the mentioning static member and non-static members, understood it in context of c++Upstanding
W
64

It's used in case of a class method. Check this reference for further details.

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

Wandering answered 6/1, 2011 at 8:21 Comment(0)
G
34

This is very good question but not as wanting as question. There is difference between 'self' and 'cls' used method though analogically they are at same place

def moon(self, moon_name):
    self.MName = moon_name

#but here cls method its use is different 

@classmethod
def moon(cls, moon_name):
    instance = cls()
    instance.MName = moon_name

Now you can see both are moon function but one can be used inside class while other function name moon can be used for any class.

For practical programming approach :

While designing circle class we use area method as cls instead of self because we don't want area to be limited to particular class of circle only .

Gareth answered 17/6, 2017 at 8:55 Comment(1)
if you like to add something more which coders looking for,if right,will approve it.Gareth
T
13

If you want to access a method via instance, keep first parameter as self. For example:

class Test:
   def hello(self, name):
      print ('hello ', name)

obj = Test()
obj.hello('Rahul')

If you want to access method using class name like we do in static class, better you use cls as first parameter in method. For example:

class Test:
       def hello(cls, name):
          print ('hello ', name)


Test.hello('Rahul')
Trussing answered 20/10, 2021 at 22:7 Comment(3)
Works with 'x = Test()' and 'x.hello('Rahul')'.Choppy
What python version is that? The second block of code doesn't work, unless the @classmethod decorator is provided.Ezzo
DOES NOT APPLY TO: python2 and python3. it is function decorator @classvariable that feeds the class as an implicit first argumentPegram
F
12

Instead of accepting a self parameter, class methods take a cls parameter that points to the class—and not the object instance—when the method is called. Since the class method only has access to this cls argument, it can’t modify object instance state. That would require access to self . However, class methods can still modify class state that applies across all instances of the class.

-Python Tricks

Formant answered 27/9, 2019 at 5:43 Comment(0)
P
1

This code snip demonstrates difference between class method and instance method.

The use of variable name (lol , is valid.

Note: variable name (self , and (cls, are style NOT syntax answered Jan 25, 2011, Baskaya

class Parent:
    greeting = 'Good morning'
    name = 'Mum'
    def greet(lol):
        return lol.greeting
    def who_am_i(lol):
        return 'i am ' + lol.name

class Child(Parent):
    greeting = 'mate'
    @classmethod
    def greet(lol):
        return lol.greeting

>>> p = Parent()
>>> print(p.greet(), p.who_am_i() )
'Good morning i am Mum'
>>> c = Child()
>>> print(c.greet(), c.who_am_i() )
'mate i am Mum'
Pegram answered 29/10, 2022 at 12:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.