473,569 Members | 2,590 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dive into Python 5.5

Hi,

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

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.updat e(dict).

someone please explain to me what happen where?

Thanks
james

Jun 13 '07 #1
3 1571
james_027 <ca********@gma il.comwrites:
class UserDict:
def __init__(self, dict=None):
self.data = {}
if dict is not None: self.update(dic t)
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(fro m)
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.updat e(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
Jun 13 '07 #2
class UserDict:
def __init__(self, dict=None):
self.data = {}
if dict is not None: self.update(dic t)

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.updat e(dict).

someone please explain to me what happen where?
You are right, this code will not work, and your suggestion is a reasonable one.

HTH,
Daniel
Jun 13 '07 #3
On Jun 13, 2:40 am, james_027 <cai.hai...@gma il.comwrote:
Hi,

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

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.updat e(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.updat e(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__.


Jun 13 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
982
by: Luis P. Mendes | last post by:
Hi, do you know if is there any 'Dive into Python' equivalent for the java language? DiP is the best I've seen and I would need to learn some basics of Java and also ways to interact between the two languages. (I'm already aware of Jpype and Jython) Luis
6
1948
by: Franz Mueller | last post by:
Hi, which of the following books would you recommend: "Dive into Python" or "Beginning Python: From Novice to Professional"? I'm an experienced C++-programmer who wants to take a look at Python. Thanks, Franz
2
2772
by: Franz Mueller | last post by:
Hi there, is there a nicer looking version of the "Dive into Python" PDF? The one from diveintopython.org looks horrible, much worse than the web-version; also the images aren't where they should be. Has anybody tried to create a nice looking version? Maybe using dblatex or something similar? (I only know of the existence of docbook,...
5
1544
by: Casey Hawthorne | last post by:
Since there was talk of if-then-else not being allowed in lambda expressions, the following is from "Dive into Python" The and-or conditional expression trick from page 41 of "Dive into Python" Wrap the arguments in lists and then take the first element. ''
3
1330
by: hanumizzle | last post by:
I find Dive Into Python generally an excellent text, and I am not surprised to see people recommending it...but I have noticed a few errors already: http://diveintopython.org/getting_to_know_python/indenting_code.html The function called fib (presumably short for Fibonacci) appears to produce factorials. Anyway, 'fib' should really be...
1
1817
by: Ben Edwards (lists) | last post by:
I have been going through Dive into Python which up to now has been excellent. I am now working through Chapter 9, XML Processing. I am 9 pages in (p182) in the 'Parsing XML section. The following code is supposed to return the whole XML document (I have put ti at the end of this email): from xml.dom import minidom xmldoc =...
2
2394
by: Fred C. Dobbs | last post by:
I feel like an idiot. I'm going thru "Dive Into Python" and running the first program - odbchelper.py My output is "pwd=secret;database=master;uid=sa;server=mpilgrim" which has all the substrings reversed from the output documented in the book. I've run the downloaded code in Komodo, PythonWin and the command line and get the same results....
51
3664
by: erikcw | last post by:
DiveIntoPython.org was the first book I read on python, and I really got a lot out of it. I need to start learning Java (to maintain a project I've inherited), and was wondering if anyone knew of any similar books for Java? Maybe once I know my way around the language, I can sneak Jython in... :-) Thanks! Erik
0
7615
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8130
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6284
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3643
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1223
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
940
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.