Dive into Python 5.5

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Jun 13 05:53:59 EDT 2007


james_027 <cai.haibin at gmail.com> writes:

> class UserDict:
>     def __init__(self, dict=None):
>         self.data = {}
>         if dict is not None: self.update(dict)

The code confusingly shadows the builtin 'dict' type with a
poorly-chosen parameter name. See if this makes things less
confusing::

    class UserDict:
        def __init__(self, from=None):
            self.data = {}
            if from is not None:
                self.update(from)

> I just don't understant this code, as it is not also mention in the
> book. the update is a method of a dict right? in my understanding
> the last statement should be self.data.update(dict).

As you point out, the 'update' method isn't defined, and the class
inherits from no base classes, so this class as written will fail in
the __init__ method when the 'self.update' attribute cannot be found.

What should be happening is that the class should inherit from the
Python dict type:

    class UserDict(dict):
        # ...

That way, the 'update' method will be inherited from the 'dict.update'
method, and likewise for all the other behaviour expected from a dict
type.

-- 
 \            "Madness is rare in individuals, but in groups, parties, |
  `\         nations and ages it is the rule."  -- Friedrich Nietzsche |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list