tags:

views:

982

answers:

3

What are advantages of using UserDict class?

I mean, what I really get if instead of

class MyClass(object):
    def __init__(self):
        self.a = 0
        self.b = 0
...
m = MyClass()
m.a = 5
m.b = 7

I will write the following:

class MyClass(UserDict):
    def __init__(self):
        UserDict.__init__(self)
        self["a"] = 0
        self["b"] = 0
...
m = MyClass()
m["a"] = 5
m["b"] = 7

Edit: If I understand right I can add new fields to an object in a runtime in both cases?

m.c = "Cool"

and

m["c"] = "Cool"
+5  A: 

Subclassing the dict gives you all the features of a dict, like if x in dict:. You normally do this if you want to extend the features of the dict, creating an ordered dict for example.

BTW: In more recent Python versions you can subclass dict directly, you don't need UserDict.

Georg
+6  A: 
Alex Martelli
A: 

gs You are right ;)

just subclass from dict and you are fine

asd
This should have been added as a comment, not an answer.
Charles Duffy