1

I understand from the question Difference between 'cls' and 'self' in Python classes? that cls is used in class methods while self is used in instance methods.

However, I used self in class methods and it is still working fine.

For example,

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

Test.hello('Tom')

What exactly does cls or self do in class methods?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
liaoming999
  • 769
  • 8
  • 14
  • 1
    Well, it's just a naming convention! – Abdul Niyas P M Nov 01 '22 at 02:24
  • 2
    Neither `self` nor `cls` is a language keyword or reserved word. You can call it `me` or `whatsyourname` or whatever you want. But as strongly as anything can be urged it is suggested to follow the convention. – sj95126 Nov 01 '22 at 02:26
  • 1
    Note that the convention is strong enough in the Python community that your text editor might color-code `self` differently. This leads a lot of people to think it's a keyword, but it's really just an ordinary variable. – Silvio Mayolo Nov 01 '22 at 04:04

1 Answers1

4

You can use any name you want. But as per the naming standard defined within PEP8(Style Guide for Python Code), it's better to name self for the first argument to instance methods and cls for the first argument to class methods.

Function and Method Arguments

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46