2014-11-04 57 views
2

我在Python中有以下类。为什么实例变量不被识别

import os,ConfigParser 

class WebPageTestConfigUtils: 

    def __init__(self, configParser=None, configFilePath=None): 
     self.configParser = ConfigParser.RawConfigParser() 
     self.configFilePath = (os.path.join(os.getcwd(),'webPageTestConfig.cfg')) 

    def initializeConfig(self): 
     configParser.read(configFilePath) 
     return configParser 

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

def main(): 
webPageTestConfigUtils = WebPageTestConfigUtils() 
webPageTestConfigUtils.initializeConfig() 
webPageTestConfigUtils.getConfigValue('testStatus') 

if __name__ =='__main__': 
main() 

执行时。这给了我错误。

NameError: global name 'configParser' is not defined

为什么python无法识别实例变量。 〜

+0

你不需要额外的'('')''左右os.path.join(os.getcwd(), 'webPageTestConfig.cfg')' – 2014-11-04 06:30:27

回答

1

这是预期的。在你的代码中,python将无法访问没有自己的类成员。下面是正确的代码:

def initializeConfig(self): 
    self.configParser.read(self.configFilePath) 
    return self.configParser 

def getConfigValue(self,key): 
    return self.configParser.get('WPTConfig', key) 
3

您正在定义

... 
self.configParser = ConfigParser.RawConfigParser() 
... 

而且使用

... 
configParser.read(configFilePath) 
... 

你要访问的self.configParser访问。