Ich will eine Instanz, die durch Parameter repräsentiert wird, welche wiederum in einem Dictionary organisiert sind.
Diese Instanz soll auch die Attribute eines Dictionaries haben, aber um weitere Attribute ergänzt werden, welche wiederum Instanzen der gleichen Klasse sind.
Das ganze wird dann ein Objekt mit dynamisch zuweisbaren Attributen die auch dynamisch wieder abgefragt werden.
Der Ansatz funktionierte auch, nur werden mir die Attribute beim Debugging im Variablenfenster von Eclipse nicht mehr angezeigt, was ich nicht verstehe und was unpraktisch ist.
Die Attribute 'key' und 'pony' kann ich mir aber auf der Konsole mit 'x.key' und 'x.pony' anzeigen lassen.
Code: Alles auswählen
pin = {'beep':1, 'blub':2}
class blop(dict):
def __init__(self):
self.key = 'key'
blopDict = self
blopDict['flip'] = 1
blopDict['flop'] = 2
class peng(blop):
def __init__(self):
blop.__init__(self)
x = peng()
setattr(x, 'pony', pin)
Die von mir im Projekt verwendete Klasse sieht so aus:
Code: Alles auswählen
import os
class PyATParam(dict):
def __init__(self, path, key):
self.key = key
self.read(path)
def read(self, path):
if os.path.isfile(path):
file = open(path, 'r')
else:
file = self.gen_default(path)
file.seek(0)
try:
at_dict = self
root = []
for line in file:
if not line.strip():
continue
elif line [0] == '{':
name = line.strip().replace("{", "")
at_dict[name] = {}
root.append(at_dict)
at_dict = at_dict[name]
elif line [0] == '}':
at_dict = root.pop()
elif line[0] != "#":
item = line.split("=")
at_key = item[0].strip()
at_dict[at_key] = item[1].strip()
file.close()
except:
PyMsgBox.PopUpMsg().dispConfirm("File /"" + path + "/" does not exist or is corrupted.", "Error", 0)
... (weitere Methoden)
Ich denke ich werde die Verschachtelung nicht mehr über dynamisch als Attribute hinzugefügte Instanzen zu lösen versuchen, sondern die Instanzen auch in dem Dictionary der erzeugenden Instanz einfügen.