Форум сайта python.su
В скрипте ниже должны записываться данные из файла конфигурации в словарь классов. Проблема в том, что в результате во всех классах прописываются данные из последней секции.
N=q
N=y
В обоих классах в данных пропишется N=y
[code python] import ConfigParser, os
def absolutepath(opfile):
config = ConfigParser.SafeConfigParser()
scriptDirectory = os.path.dirname(os.path.realpath(__file__))
settingsFilePath = os.path.join(scriptDirectory, opfile)
config.readfp(open(settingsFilePath,"r"))
return config
print 'import', opfile
def writedata(ndict,nclass,namefile):
opfile=absolutepath(namefile)
for section in opfile.sections():
ndict[section]=nclass
for option in opfile.options(section):
ndict[section].options[option]=opfile.get(section,option)
print section,ndict[section].options [/code]
Офлайн
я предполагаю что вы в функцию writedata параметром nclass передаете объект (экземпляр класса)
это тоже самое если бы вы делали так
def writedata(ndict,nclass,namefile): opfile=absolutepath(namefile) for section in opfile.sections(): for option in opfile.options(section): nclass.options[option]=opfile.get(section,option) print section,nclass.options
Guljacaто нужно так
должны записываться данные из файла конфигурации в словарь классов
# . . . class A: # . . . def writedata(ndict,nclass,namefile): opfile=absolutepath(namefile) for section in opfile.sections(): ndict[section]=nclass() for option in opfile.options(section): ndict[section].options[option]=opfile.get(section,option) print section,ndict[section].options
class A: def __init__(self): self.options = {} ndict = {} def f(d, c): for i in range(3): d[i] = c for j in range(i, 5): d[i].options[j] = j*2-i return d t = f(ndict, A()) for i, j in t.items(): print(i, j.options)
0 {0: 0, 1: 1, 2: 2, 3: 4, 4: 6}
1 {0: 0, 1: 1, 2: 2, 3: 4, 4: 6}
2 {0: 0, 1: 1, 2: 2, 3: 4, 4: 6}
class A: def __init__(self): self.options = {} ndict = {} def f(d, c): for i in range(3): d[i] = c() # с скобками for j in range(i, 5): d[i].options[j] = j*2-i return d t = f(ndict, A) # без скобок for i, j in t.items(): print(i, j.options)
0 {0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
1 {1: 1, 2: 3, 3: 5, 4: 7}
2 {2: 2, 3: 4, 4: 6}
Отредактировано terabayt (Авг. 10, 2016 02:11:30)
Офлайн