I was asked during an interview what is the difference between the following two ways to access a class’ attribute:
JavaScript
x
11
11
1
class Klass:
2
x = 10
3
4
@staticmethod
5
def foo():
6
return Klass.x
7
8
@classmethod
9
def bar(cls):
10
return cls.x
11
PS: I know the difference between classmethod
and staticmethod
.
Advertisement
Answer
Using cls would also work with inheritance,
JavaScript
1
8
1
class Klass2(Klass):
2
x = 5
3
4
print(Klass2().foo())
5
10
6
print(Klass2().bar())
7
5
8
Though there might be more differences