Python 类静态方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12735392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python class static methods
提问by ilyaw77
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).
我得到了一个错误: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)
- 我究竟做错了什么?静态方法不应该可以通过类名调用吗?
- 我真的需要一个实用程序类,还是有其他方法可以在 Python 中实现相同的功能?
- 如果我尝试更改 main 中的代码,我会得到:
TypeError: GetFilePath() takes exactly 1 argument (2 given)
The new main:
新的main:
from FileUtility import *
def main():
objFile = FileUtility()
path = 'H:\config_file_list.txt'
dir = objFile.GetFilePath(path)
print dir
采纳答案by Collin
You're getting the error because you're taking a selfargument in each of those functions. They're static, you don't need it.
您收到错误是因为您self在每个函数中都使用了一个参数。它们是静态的,你不需要它。
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.
然而,'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
Now, in your other python files (assuming fileutility.py is in the same directory or on the PYTHONPATH)
现在,在您的其他 python 文件中(假设 fileutility.py 在同一目录中或在PYTHONPATH)
import fileutility
fileutility.get_file_size("myfile.txt")
fileutility.get_file_path("that.txt")
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.
它没有特别提到静态方法,但如果您来自不同的语言PEP 8,python 风格指南是一本很好的读物,并介绍了 Python 程序员的思维方式。
回答by Ignacio Vazquez-Abrams
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.
你真的不应该在 Python 中创建静态方法。您应该做的是将它们放在全局函数级别,然后在调用它们时访问它们所在的模块。
foo.py:
foo.py:
def bar():
return 42
baz.py:
巴兹.py:
import foo
print foo.bar()
回答by Thomas Orozco
In python, java-like (or whatever) staticmethods are not widely used as they don't really have a purpose.
在python中,类java(或其他)static方法没有被广泛使用,因为它们并没有真正的目的。
Instead, you should simply define your "methods" as functions in a module:
相反,您应该简单地将“方法”定义为模块中的函数:
#module1.py
def fun1():
return do_stuff()
def fun2(arg):
return do_stuff_with_arg(arg)
#main.py
import module1
if __name__ == '__main__':
a = module1.fun()
print module1.fun2(a)
回答by Hedlok
Static methods don't get the object passed in as the first parameter (no object)
静态方法不获取作为第一个参数传入的对象(无对象)
remove the selfparameter and the calls should work.
The import problem is relevant too.
And the static comment relevant too.
删除self参数,调用应该可以工作。进口问题也很重要。静态评论也相关。
回答by Pollux31
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 :
所以结果是:
dir = FileUtility().GetFilePath(path)
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.
@staticmethod 不需要,因为您使用的是标准函数,而不是静态函数。但在你的情况下,结果是一样的。
回答by Saleem Khan
Just remove selfin methods definition. Your intention is to use as static. Self is to work with instance of that class.
只需self在方法定义中删除即可。您的意图是用作静态。Self 是使用该类的实例。
回答by Shreyas sreenivas
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:
只需删除函数定义中的 self 即可。由于您使用静态函数,因此您无需将 self 作为函数的参数传递。所以你的类和函数应该是这样的:
class FileUtility():
@staticmethod
def GetFileSize(fullName):
fileSize = os.path.getsize(fullName)
return fileSize
@staticmethod
def GetFilePath(fullName):
filePath = os.path.abspath(fullName)
return filePath

