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.
Advertisement
Answer
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