我是靠谱客的博主 无心裙子,最近开发中收集的这篇文章主要介绍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中正确定义静态实用工具类所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部