刷新或重新运行一个class in Python 2.7
Refreshing or re-running a class in Python 2.7
我有一个 class 从配置文件中检索值和添加它们的函数。我调用 class,然后更改值 运行 函数来编写它们。当我之后调用 class 时,值不会更新。我检查配置文件,值已更改。有没有办法让它每次调用都重新读取数据?
这是一个简化版本...
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 属性,因此它只在您定义 class 时创建一次。改为这样做:
class read_conf_values(object):
def __init__(self):
parser = ConfigParser.ConfigParser()
parser.read('configuration.conf')
self.a = parser.get('asection', 'a')
然后每次创建实例时都会设置一个新的a
属性(使用read_conf_values()
)。您可以在此站点上找到许多其他关于 class 和实例属性之间的区别的问题。
我有一个 class 从配置文件中检索值和添加它们的函数。我调用 class,然后更改值 运行 函数来编写它们。当我之后调用 class 时,值不会更新。我检查配置文件,值已更改。有没有办法让它每次调用都重新读取数据?
这是一个简化版本...
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 属性,因此它只在您定义 class 时创建一次。改为这样做:
class read_conf_values(object):
def __init__(self):
parser = ConfigParser.ConfigParser()
parser.read('configuration.conf')
self.a = parser.get('asection', 'a')
然后每次创建实例时都会设置一个新的a
属性(使用read_conf_values()
)。您可以在此站点上找到许多其他关于 class 和实例属性之间的区别的问题。