在Python 2.7中刷新或重新运行类

在Python 2.7中刷新或重新运行类,python,function,python-2.7,class,configuration,Python,Function,Python 2.7,Class,Configuration,我有一个从配置文件中检索值的类和一个添加值的函数。我调用该类,更改值,然后运行函数来编写它们。当我随后调用该类时,值不会更新。我检查了配置文件,值已经更改。有没有办法让它每次调用时都重新读取数据 这是一个简化的版本 import ConfigParser class read_conf_values(): parser = ConfigParser.ConfigParser() parser.read('configuration.conf') a = parser.g

我有一个从配置文件中检索值的类和一个添加值的函数。我调用该类,更改值,然后运行函数来编写它们。当我随后调用该类时,值不会更新。我检查了配置文件,值已经更改。有没有办法让它每次调用时都重新读取数据

这是一个简化的版本

import ConfigParser

class read_conf_values():
    parser = ConfigParser.ConfigParser()
    parser.read('configuration.conf')
    a = parser.get('asection', 'a')


def confwrite(newconfig):
    file = open("configuration.conf", "w")
    file.write(newconfig)
    file.close()

conf = read_conf_values()
print conf.a
newvalue = raw_input('Enter a new value for a?')
newconfig = '[asection]\na = '+newvalue
confwrite(newconfig)
conf = read_conf_values()
print conf.a

我必须编写文件,而不是使用configparser来添加值,因为实际配置没有节。我可以用一个假的部分模块来读它,但我必须把它写成一个文本文件。这个例子也有同样的问题。

您的
a
是一个类属性,因此在定义类时只创建一次。改为这样做:

class read_conf_values(object):
    def __init__(self):
        parser = ConfigParser.ConfigParser()
        parser.read('configuration.conf')
        self.a = parser.get('asection', 'a')

然后,每次创建实例时(使用
read\u conf\u values()
)都会设置一个新的
a
属性。你可以在这个网站上找到很多关于类和实例属性之间区别的其他问题。

是的,有一种方法。在您提供现有实现的详细信息之前,我将尽可能详细地介绍这些内容。好的,我马上介绍:-)您使用的是configparser吗?是的,我已经更新了我的问题以解释更多内容。谢谢,这非常有效。关于课堂,我有很多东西要学。