Hi,
class UserDict:
def __init__(self, dict=None):
self.data = {}
if dict is not None: self.update(dict)
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).
someone please explain to me what happen where?
Thanks
james
This is what "Dive" says:
---
To explore this further, let's look at the UserDict
class in the UserDict module...In particular, it's stored in the lib
directory in your Python installation.
---
So you can actually locate the file UserDict.py on your computer and
look at the code. If you don't want to do that, then the following is
an explanation of what's going on with that code.
Suppose you have a class like this:
class Dog(object):
def __init__(self):
self.update()
When __init__ executes, the only line in __init__ says go look in self
for the method update() and execute it. That means the Dog class
probably has at least one additional method:
class Dog(object):
def __init__(self):
self.update()
def update(self):
print "hello"
So if you wrote:
d = Dog()
the output would be:
hello
Ok, now suppose you add a line to __init__:
class Dog(object):
def __init__(self):
self.data = {}
self.update()
def update(self):
print "hello"
Does the new line in __init__ affect the line self.update() in any
way? Is there necessarily any connection between self.data and
update()? No.
However, if you look at the actual code for UserDict, you can see that
inside the method update(), items are added to self.data, so there is
a connection.
Then the question is: why didn't the person who wrote the class just
do the following in __init__:
self.data.update(dict)
Well, as it turns out, adding items to self.data is not that straight
forward. self.data is a dict type and dict types have an update()
method that requires another dict as an argument. But the 'dict'
parameter variable in __init__ could be sent a dict type or it could
be sent another instance of UserDict. So, the code to add items to
self.data got complicated enough that the writer of the class decided
to move the code into its own method. Note that just because the
parameter variable is named 'dict' does not mean the argument sent to
the function is a dict type. For instance, you could write this:
dict = "hello world"
As you can see, the variable named 'dict' does not refer to a dict
type. Using a python type as a variable name is a horrible and
confusing thing to do, so don't do it in your code.
In addition, the writer of the class wanted to provide an update()
method for the UserDict class, which could be called at any time, so
instead of having to write the same code in two places: once in
__init__ to initialize an instance with a given dict and a second time
inside the update() method, the programmer wrote the code once in its
own method and then called the method from __init__.