Newbie question about Class
Gabriel Genellina
gagsl-py at yahoo.com.ar
Tue Feb 13 10:53:32 EST 2007
En Tue, 13 Feb 2007 03:56:21 -0300, <JStoneGT at aol.com> escribió:
> I'm reading the book of "Dive into Python" and got these code pieces:
> class UserDict:
> def __init__(self, dict=None): self.data = {}
> if dict is not None: self.update(dict)
> My question is,for the statement of:
> if dict is not None: self.update(dict)
> Why it's not this one below?
> if dict is not None: self.data.update(dict)
> Thanks.
The idea behind that class is to act "as-if" it were a real dictionary.
Dicts have an update method, and UserDict should too. But it's not listed
in the book (should appear a few lines below that code); this is a
possible implementation:
def update(self, other):
for key in other.keys():
self.data[key] = other[key]
Given this method, __init__ works fine.
Using self.data.update(dict) is OK if the dict argument is a real
dictionary, but not if it's another UserDict.
--
Gabriel Genellina
More information about the Python-list
mailing list