I use the previously described technique to turn a dictionary into an object so that I can access the elements of the dictionary with a point (.) Of concept as instance variables.
This is what I do:
myData = {'apple':'1', 'banana':'2', 'house':'3', 'car':'4', 'hippopotamus':'5'}
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
k = Struct(**myData)
So now I can do:
print k.apple
and the result:
1
This works, but problems begin if I try to add some other methods to the "Struct" class. For example, let's say that I add a simple method that simply creates a variable:
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
def testMe(self):
self.myVariable = 67
If I do this:
k.testMe()
My object dictionary is broken, "myVariable" is inserted as a key with a value of "67". So, if I:
print k.__dict__
I get:
{'apple': '1', 'house': '3', 'myVariable': 67, 'car': '4', 'banana': '2', 'hippopotamus': '5'}
? , , . ?
:
Python dict ?
.