我想创建一种实用程序类,它只包含可由名称类前缀调用的静态方法.看起来我做错了什么:)
这是我的小班:
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
Run Code Online (Sandbox Code Playgroud)
现在我的"主要"方法:
from FileUtility import *
def main():
path = 'C:\config_file_list.txt'
dir = FileUtility.GetFilePath(path)
print dir
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:unbound method GetFilePath() must be called with FileUtility instance as first argument (got str instance instead).
这里有一些问题:
TypeError: GetFilePath() takes exactly 1 argument (2 given)新的main:
from FileUtility import *
def main():
objFile = FileUtility()
path = 'H:\config_file_list.txt'
dir = objFile.GetFilePath(path)
print dir
Run Code Online (Sandbox Code Playgroud)
Col*_*lin 87
你得到错误是因为你self在每个函数中都有一个参数.它们是静态的,你不需要它.
然而,"pythonic"这样做的方法不是让一个类充满静态方法,而是让它们在模块中使它们成为自由函数.
#fileutility.py:
def get_file_size(fullName):
fileSize = os.path.getsize(fullName)
return fileSize
def get_file_path(fullName):
filePath = os.path.abspath(fullName)
return filePath
Run Code Online (Sandbox Code Playgroud)
现在,在你的其他python文件中(假设fileutility.py在同一个目录中或在PYTHONPATH)
import fileutility
fileutility.get_file_size("myfile.txt")
fileutility.get_file_path("that.txt")
Run Code Online (Sandbox Code Playgroud)
它没有特别提到静态方法,但如果你来自另一种语言PEP 8,那么python风格指南就是对python程序员思考方式的一个很好的阅读和介绍.
你真的不应该在Python中创建静态方法.您应该做的是将它们置于全局功能级别,然后在调用它们时访问它们所在的模块.
foo.py:
def bar():
return 42
Run Code Online (Sandbox Code Playgroud)
baz.py:
import foo
print foo.bar()
Run Code Online (Sandbox Code Playgroud)