Search code examples
pythonstatic-methods

Why I got TypeError if calling staticmethod without class-body?


Why it happens? is this "binding behavior”? using staticmethod in class body

>>> class Test:
    
         @staticmethod
         def test(msg="asd"):
             print(msg)
        
>>> test = Test()
>>> test.test()
asd

but when I using it without, got error:

>>> @staticmethod
    def test(msg=""):
         print(msg)
    
>>> test
<staticmethod object at 0x10dde9be0>
>>> test()
Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
    exec(exp, global_vars, local_vars)
  File "<input>", line 1, in <module>
TypeError: 'staticmethod' object is not callable

Solution

  • A static method is a method that is bound to a class but does not require the class instance to function. For example, you may have a class built around a file type to retrieve raw data from a source file and pass it to a lexer, your constructor could have you pass in the raw file however you may want another function to open the file, validate it and retrieve the data. In this case, you could use a static function within the class as the function is related to the class but doesn't require the class to function (in this case it would return the actual class).

    A code example:

    
    class PythonFile:
    
       def __init__(self, raw_data):
    
          self._raw_data = raw_data
          self._lexer = None
    
       @staticmethod
       def open(fp):
          with open(fp, "r") as rFile:
             data = rFile.read()
          # validate, etc...
          return PythonFile(data)
    
       def lex(self):
          self._lexer = PythonLex(self._raw_data)
          return self._lexer.get_master_block_array()
    
    # etc, etc...
    
    python_file = PythonFile.open("some\\path.py")
    print(python_file.lex())
    
    

    ItzTheDodo.