我是靠谱客的博主 无心裙子,这篇文章主要介绍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几乎总是更好.

然后,configParser是cls参数的属性:

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

来源: https://codeday.me/bug/20191121/2049101.html

最后

以上就是无心裙子最近收集整理的关于python如何设计工具类_如何在Python中正确定义静态实用工具类的全部内容,更多相关python如何设计工具类_如何在Python中正确定义静态实用工具类内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(124)

评论列表共有 0 条评论

立即
投稿
返回
顶部