1 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
由于configParser在大多數(shù)情況下都像 dict 一樣,我們在這里可以做的是使用key不同的代碼塊來確保有唯一的塊。
這是一個(gè)簡單的測試來展示它的實(shí)際效果:
import configparser
class Container:
configs=[] # keeps a list of all initialized objects.
def __init__(self, **kwargs):
for k,v in kwargs.items():
self.__setattr__(k,v) # Sets each named attribute to their given value.
Container.configs.append(self)
# Initializing some objects.
Container(
Name="Test-Object1",
Property1="Something",
Property2="Something2",
Property3="Something3",
)
Container(
Name="Test-Object2",
Property1="Something",
Property2="Something2",
Property3="Something3",
)
Container(
Name="Test-Object2",
Property1="Something Completely different",
Property2="Something Completely different2",
Property3="Something Completely different3",
)
config = configparser.ConfigParser()
for item in Container.configs: # Loops through all the created objects.
config[item.Name] = item.__dict__ # Adds all variables set on the object, using "Name" as the key.
with open("example.ini", "w") as ConfigFile:
config.write(ConfigFile)
在上面的示例中,我創(chuàng)建了三個(gè)包含要由 configparser 設(shè)置的變量的對象。但是,第三個(gè)對象Name與第二個(gè)對象共享變量。這意味著第三個(gè)將在寫入 .ini 文件時(shí)“覆蓋”第二個(gè)。
例子.ini :
[Test-Object1]
name = Test-Object1
property1 = Something
property2 = Something2
property3 = Something3
[Test-Object2]
name = Test-Object2
property1 = Something Completely different
property2 = Something Completely different2
property3 = Something Completely different3
添加回答
舉報(bào)