I want to create a kind of utility class which contains only static methods which are callable by the name class prefix. Looks like I'm doing something wrong :)
Here is my small class:
class FileUtility():
@staticmethod
def GetFileSize(self, fullName):
fileSize = os.path.getsize(fullName)
return fileSize
@staticmethod
def GetFilePath(self, fullName):
filePath = os.path.abspath(fullName)
return filePath
Now my "main" method:
from FileUtility import *
def main():
path = 'C:\config_file_list.txt'
dir = FileUtility.GetFilePath(path)
print dir
and I got an error: unbound method GetFilePath() must be called with FileUtility instance as first argument (got str instance instead)
.
A have a few questions here:
- What am I doing wrong? Should not the static method be callable by classname?
- Do I really need a utility class, or are there other ways to achieve the same in Python?
- If I try to change the code in main I'm getting:
TypeError: GetFilePath() takes exactly 1 argument (2 given)
The new main
:
from FileUtility import *
def main():
objFile = FileUtility()
path = 'H:\config_file_list.txt'
dir = objFile.GetFilePath(path)
print dir
You're getting the error because you're taking a
self
argument in each of those functions. They're static, you don't need it.However, the 'pythonic' way of doing this is not to have a class full of static methods, but to just make them free functions in a module.
Now, in your other python files (assuming fileutility.py is in the same directory or on the
PYTHONPATH
)It doesn't mention static methods specifically, but if you're coming from a different language, PEP 8, the python style guide is a good read and introduction to how python programmers think.
Just remove the self in the function definition. Since your using the static functions so you need not pass self as an argument for the functions. So your class and function should be like this:
You really shouldn't be creating static methods in Python. What you should be doing is putting them at the global function level, and then accessing the module they're in when you call them.
foo.py:
baz.py:
In python, java-like (or whatever)
static
methods are not widely used as they don't really have a purpose.Instead, you should simply define your "methods" as functions in a module:
If you want to use your functions defined in the class, you have just to create an instance of your class and apply the function.
So the result is :
Just add () after your class name.
@staticmethod is not needed as you are using standard function, not static. But in your case the result is the same.
Just remove
self
in methods definition. Your intention is to use as static. Self is to work with instance of that class.