0
class First:
    @classmethod
    def hello(self):
        print(123)

class Second:  
    @classmethod
    def hello(cls):
        print(123)

obj1 = First()
obj2 = Second()

print(obj1.hello())
print(obj1.hello())

I am not getting any error while calling obj1 (with self as argument) and obj2 (with cls as argument). Why not? Is the classmethod decorator able to use cls/self?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ashok Ramesh
  • 121
  • 2
  • 7
  • 5
    It's just a *name*. We call the instance in an instance method `self` **by convention**, and the class in a class method `cls` the same, but you could switch the names, or use `foo`, or anything else. As long as you're consistent between definition and usage, it will work like any other parameter. – jonrsharpe Jul 01 '19 at 12:44

1 Answers1

0

One will be understood by every reasonably experienced Python programmer.
The other one will confuse every reasonably experienced Python programmer.

The first argument of a classmethod is a class and should be called cls. You can give it any other name in your code, but that's a bad idea, because it still is a class.

Roland Weber
  • 1,865
  • 2
  • 17
  • 27