Problems converting a dictionary to an object

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:

# Initial dictionary
myData = {'apple':'1', 'banana':'2', 'house':'3', 'car':'4', 'hippopotamus':'5'}

# Create the container class
class Struct:
    def __init__(self, **entries):
        self.__dict__.update(entries)

# Finally create the instance and bind the dictionary to it
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 ?

.

+4
1

__dict__. .__getattr__ ( print k.apple) __setattr__ ( k.apple=2):

# Initial dictionary
myData = {'apple':'1', 'banana':'2', 'house':'3', 'car':'4', 'hippopotamus':'5'}

# Create the container class
class Struct:
    _dict = {}
    def __init__(self, **entries):
        self._dict = entries

    def __getattr__(self, name):
        try:
            return self._dict[name]
        except KeyError:
            raise AttributeError(
                "'{}' object has no attribute or key '{}'".format(
                    self.__class__.__name__, name))


    def __setattr__(self, name, value):
        if name in self._dict:
            self._dict[name] = value
        else:
            self.__dict__[name] = value

    def testMe(self):
        self.myVariable = 67

    def FormattedDump(self):
        return str(self._dict)

# Finally create the instance and bind the dictionary to it
k = Struct(**myData)

print k.apple
print k.FormattedDump()
k.testMe()
k.apple = '2'
print k.FormattedDump()

, FormattedDump() , :

# Initial dictionary
myData = {'apple':'1', 'banana':'2', 'house':'3', 'car':'4', 'hippopotamus':'5'}

# Create the container class
class Struct:
    def __init__(self, **entries):
        self.__dict__.update(entries)
        self.public_names = entries.keys()

    def testMe(self):
        self.myVariable = 67

    def GetPublicDict(self):
        return {key:getattr(self, key) for key in self.public_names}
    def FormattedDump(self):
        return str(self.GetPublicDict())

# Finally create the instance and bind the dictionary to it
k = Struct(**myData)

print k.apple
print k.FormattedDump()
k.testMe()
k.apple = '2'
print k.FormattedDump()
+2

All Articles