I just can\'t see why do we need to use @staticmethod. Let\'s start with an exmaple.
class test1:
def __init__(self,value):
self.value=value
Today I suddenly find a benefit of using @staticmethod
.
If you created a staticmethod within a class, you don't need to create an instance of the class before using the staticmethod.
For example,
class File1:
def __init__(self, path):
out=self.parse(path)
def parse(self, path):
..parsing works..
return x
class File2:
def __init__(self, path):
out=self.parse(path)
@staticmethod
def parse(path):
..parsing works..
return x
if __name__=='__main__':
path='abc.txt'
File1.parse(path) #TypeError: unbound method parse() ....
File2.parse(path) #Goal!!!!!!!!!!!!!!!!!!!!
Since the method parse
is strongly related to the classes File1
and File2
, it is more natural to put it inside the class. However, sometimes this parse
method may also be used in other classes under some circumstances. If you want to do so using File1
, you must create an instance of File1
before calling the method parse
. While using staticmethod in the class File2
, you may directly call the method by using the syntax File2.parse
.
This makes your works more convenient and natural.