1

Are the following methods always equivalent within a class? In other words, within MyClass can I interchangeably use cls in a class method and MyClass in a static method?

class MyClass:

    @classmethod
    def my_class_method(cls):
        cls.attribute = "a"

    @staticmethod
    def my_non_class_method():
        MyClass.attribute = "b"
martineau
  • 112,593
  • 23
  • 157
  • 280
user1315621
  • 2,548
  • 6
  • 31
  • 60

2 Answers2

2

cls isn't a keyword, just like self isn't a keyword.

No, cls and MyClass aren't interchangeable unless you are positive that MyClass doesn't have any subclasses.

The point of a @classmethod is to get the right class type if you call it through a subclass. for example

class Base:
    @classmethod
    def f(cls):
        print(f'class is {cls}')

class Sub(Base):
    pass

Sub.f()  # calls Base.f with cls=Sub

If you don't need the actual class type, then you can use @staticmethod instead.

Ryan Haining
  • 32,906
  • 11
  • 104
  • 160
-2

Yes. Heck, you could use MyClass in the class method, too, if you really felt like it.

Tim Roberts
  • 34,376
  • 3
  • 17
  • 24