python - 如何在 Python 中正确定义静态实用程序类

标签 python

我想编写一个实用程序类来读取 python 中的配置文件。

import os,ConfigParser

class WebPageTestConfigUtils:

    configParser = ConfigParser.RawConfigParser()
    configFilePath = (os.path.join(os.getcwd(),'webPageTestConfig.cfg'))

    @staticmethod
    def initializeConfig():
        configParser.read(self.configFilePath)

    @staticmethod
    def getConfigValue(key):
        return configParser.get('WPTConfig', key)

def main():
    WebPageTestConfigUtils.initializeConfig()
    print WebPageTestConfigUtils.getConfigValue('testStatus')

if  __name__ =='__main__':
    main()

执行时会抛出错误。

NameError: 全局名称“configParser”未定义

为什么python不能识别静态成员。

最佳答案

一般来说,使用 @classmethod 几乎总是优于 @staticmethod

然后,configParsercls 参数的一个属性:

class WebPageTestConfigUtils(object):

    configParser = ConfigParser.RawConfigParser()
    configFilePath = (os.path.join(os.getcwd(),'webPageTestConfig.cfg'))

    @classmethod
    def initializeConfig(cls):
        cls.configParser.read(cls.configFilePath)

    @classmethod
    def getConfigValue(cls, key):
        return cls.configParser.get('WPTConfig', key)

另请注意,您对 self 的使用已替换为 cls

关于python - 如何在 Python 中正确定义静态实用程序类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26729078/

相关文章:

python - 分组依据,在 Pandas 中

python - 通过仅下载网页的相关部分来抓取标题

Python findall、正则表达式

python - 带有 Gui 的 Websocket

python - 如何替换数据框中的 Year 并在 Pandas 中将该值乘以 12

python - 初始化经过训练的 keras 网络的单层并获得预测

python - 从开始/结束坐标获取 NumPy 切片

python - SQL表中的值发生变化时如何执行Python函数?

python - 嵌套 for 循环 n 次以将列表的子列表添加到自身

python - 使用 __import__ 从同名模块导入对象