0

I was asked during an interview what is the difference between the following two ways to access a class' attribute:

class Klass:
    x = 10

    @staticmethod
    def foo():
        return Klass.x

    @classmethod
    def bar(cls):
        return cls.x

PS: I know the difference between classmethod and staticmethod.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Ivan Dives
  • 477
  • 5
  • 9
  • 1
    Does this answer your question? [Difference between staticmethod and classmethod](https://stackoverflow.com/questions/136097/difference-between-staticmethod-and-classmethod) – Federico Baù Dec 24 '20 at 14:47
  • no) I wasn't asking what's the difference between classmethod and staticmethod) – Ivan Dives Dec 24 '20 at 14:50
  • 1
    @IvanDives What are you asking then? `what is the difference between the following two ways to access class attribute` Isn't this your question? – Abhishek Rai Dec 24 '20 at 14:56
  • 2
    Just a hunch : I'd say that it will have impacts when you are taking class inheritance in mind... (The second way of accessing arguments would probably allow you to access attributes of other inherited/parent classes) – tgrandje Dec 24 '20 at 14:57

1 Answers1

2

Using cls would also work with inheritance,

class Klass2(Klass):
  x = 5

print(Klass2().foo())
10
print(Klass2().bar())
5

Though there might be more differences

Ron Serruya
  • 3,988
  • 1
  • 16
  • 26
  • Both `static-` and `classmethod` are (usually) called ***on the class***. So change `Klass2()` to `Klass2` – Tomerikoo Dec 24 '20 at 15:48