Found a good one to explain:
How @staticmethod and @classmethod are different.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class Kls(object):
no_inst = 0 #( this would be class level variable)
def __init__(self, data):
self.data = data # (this would be instance variable)
def printd(self):
print(self.data)
@staticmethod
def smethod(*arg): # no class/inst , just pass the arg as it is
print(‘Static:’, arg)
@classmethod
def cmethod(*arg): # always pass the class as the first argument
print(‘Class:’, arg)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
>>> ik = Kls(23)
>>> ik.printd()
23
>>> ik.smethod()
Static: ()
>>> ik.cmethod()
Class: (<class ‘__main__.Kls’>,)
>>> Kls.printd()
TypeError: unbound method printd() must be called with Kls instance as first argument (got nothing instead)
>>> Kls.smethod()
Static: ()
>>> Kls.cmethod()
Class: (<class ‘__main__.Kls’>,)
|
Rerferences