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
  • 119,623
  • 25
  • 170
  • 301
user1315621
  • 3,044
  • 9
  • 42
  • 86

2 Answers2

3

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
  • 35,360
  • 15
  • 114
  • 174
-2

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

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30