Python 类静态方法 [英] Python class static methods

查看:48
本文介绍了Python 类静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一种实用程序类,它只包含可通过名称类前缀调用的静态方法.看起来我做错了什么:)

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 :)

这是我的小班:

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

现在我的主要"方法:

from FileUtility import *
def main():
        path = 'C:\config_file_list.txt'
        dir = FileUtility.GetFilePath(path)
        print dir

并且我收到一个错误:必须使用 FileUtility 实例作为第一个参数调用未绑定的方法 GetFilePath()(改为使用 str 实例).

and I got an error: unbound method GetFilePath() must be called with FileUtility instance as first argument (got str instance instead).

这里有几个问题:

  1. 我做错了什么?静态方法不应该可以通过类名调用吗?
  2. 我真的需要一个实用程序类,还是有其他方法可以在 Python 中实现相同的功能?
  3. 如果我尝试更改 main 中的代码,我会得到:TypeError: GetFilePath() 只需要 1 个参数(给定 2 个)

新的main:

from FileUtility import *
def main():
    objFile = FileUtility()
    path = 'H:\config_file_list.txt'
    dir = objFile.GetFilePath(path)
    print dir

推荐答案

您收到错误是因为您在每个函数中都采用了 self 参数.它们是静态的,您不需要它.

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.

然而,'pythonic' 的方法不是让一个类充满静态方法,而是让它们成为模块中的自由函数.

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.

#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

现在,在您的其他 python 文件中(假设 fileutility.py 在同一目录中或在 PYTHONPATH 上)

Now, in your other python files (assuming fileutility.py is in the same directory or on the PYTHONPATH)

import fileutility

fileutility.get_file_size("myfile.txt")
fileutility.get_file_path("that.txt")

它没有特别提到静态方法,但如果你来自不同的语言,PEP 8,python 风格指南是一本很好的读物,介绍了 Python 程序员的思维方式.

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.

这篇关于Python 类静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆