Beginning Question about Python functions, parameters...

A

astral orange

Hi, I am trying to teach myself Python and have a good book to help me
but I am stuck on something and I would like for someone to explain
the following piece of code for me and what it's actually doing.
Certain parts are very clear but once it enters the "def store(data,
full_name): ...." function and the "def lookup()..." function things
get a little confusing for me. Specifically, lines 103-108 *and* Lines
110-111.

Lastly, I am not sure how to print the results I've put into this
program either, the book I'm reading doesn't tell me. As you can tell,
I am a beginner and I don't truly understand everything that is going
on here...a lot, but not all....

Here is the code:

92 def init(data):
93 data['first'] = {}
94 data['middle'] = {}
95 data['last'] = {}
96
97 def store(data, full_name):
98 names = full_name.split()
100 if len(names) == 2: names.insert(1, '')
101 labels = 'first', 'middle', 'last'
103 for label, name in zip(labels, names):
104 people = lookup(data, label, name)
105 if people:
106 people.append(full_name)
107 else:
108 data[label][name] = [full_name]
109
110 def lookup(data, label, name):
111 return data[label].get(name)
112
113
114 MyNames = {}
115 init(MyNames)
116 store(MyNames, 'John Larry Smith')
117 lookup(MyNames, 'middle', 'Smith')
 
N

Neo

astral said:
Hi, I am trying to teach myself Python and have a good book to help me
but I am stuck on something and I would like for someone to explain
the following piece of code for me and what it's actually doing.
Certain parts are very clear but once it enters the "def store(data,
full_name): ...." function and the "def lookup()..." function things
get a little confusing for me. Specifically, lines 103-108 *and* Lines
110-111.

Lastly, I am not sure how to print the results I've put into this
program either, the book I'm reading doesn't tell me. As you can tell,
I am a beginner and I don't truly understand everything that is going
on here...a lot, but not all....

Here is the code:

92 def init(data):
93 data['first'] = {}
94 data['middle'] = {}
95 data['last'] = {}
96
97 def store(data, full_name):
98 names = full_name.split()
100 if len(names) == 2: names.insert(1, '')
101 labels = 'first', 'middle', 'last'
103 for label, name in zip(labels, names):
104 people = lookup(data, label, name)
105 if people:
106 people.append(full_name)
107 else:
108 data[label][name] = [full_name]
109
110 def lookup(data, label, name):
111 return data[label].get(name)
112
113
114 MyNames = {}
115 init(MyNames)
116 store(MyNames, 'John Larry Smith')
117 lookup(MyNames, 'middle', 'Smith')

If it tells you so I'm not really sure its a good book - partially for
teaching you into the unpythonic way to do things (above stuff, if its
not a counter example, should really go into a class)

Have you tried the tutorial first? Its online and very easy to follow
from the very beginning but you can also skip parts if you are sure you
already understand it:

http://docs.python.org/tutorial/

HTH
Tino
 
D

Diez B. Roggisch

astral said:
Hi, I am trying to teach myself Python and have a good book to help me
but I am stuck on something and I would like for someone to explain
the following piece of code for me and what it's actually doing.
Certain parts are very clear but once it enters the "def store(data,
full_name): ...." function and the "def lookup()..." function things
get a little confusing for me. Specifically, lines 103-108 *and* Lines
110-111.

Lastly, I am not sure how to print the results I've put into this
program either, the book I'm reading doesn't tell me. As you can tell,
I am a beginner and I don't truly understand everything that is going
on here...a lot, but not all....

Here is the code:

92 def init(data):
93 data['first'] = {}
94 data['middle'] = {}
95 data['last'] = {}
96
97 def store(data, full_name):
98 names = full_name.split()
100 if len(names) == 2: names.insert(1, '')
101 labels = 'first', 'middle', 'last'
103 for label, name in zip(labels, names):

The zip-function takes n iterables, and produces a list with n-tuples out of
it. Type this into the python-prompt:
zip([1, 2, 3], ["a", "b", "c"])

The other thing here is tuple-unpacking. If you know that something has a
specific length, you can unpack it into distinct values like this:
20

Now

for label, name in zip(labels, names):


does

- create a list of tuples, each tuple having two elements, the first being
the label, the second a name
- loops over this list
- for each item in the list (remember, it's a 2-tuple!), unpack it into
label and name



104 people = lookup(data, label, name)
105 if people:
106 people.append(full_name)
107 else:
108 data[label][name] = [full_name]
109
110 def lookup(data, label, name):
111 return data[label].get(name)

Data here is expected to be a dictionary of dictionaries. The first level of
keys are the labels. The second is the name. It is expected that labels
always exist, but names might be empty, so instead of writing

return data[label][name]

it uses get(name) on a dict which will return the value for the key, or
None:


That being said, I agree with Neo that this introduction seems to be rather
bad.

Diez
 
J

j

astral orange schrieb:


Hi, I am trying to teach myself Python and have a good book to help me
but I am stuck on something and I would like for someone to explain
the following piece of code for me and what it's actually doing.
Certain parts are very clear but once it enters the "def store(data,
full_name): ...." function and the "def lookup()..." function things
get a little confusing for me. Specifically, lines 103-108 *and* Lines
110-111.
Lastly, I am not sure how to print the results I've put into this
program either, the book I'm reading doesn't tell me. As you can tell,
I am a beginner and I don't truly understand everything that is going
on here...a lot, but not all....
Here is the code:
 92 def init(data):
 93     data['first'] = {}
 94     data['middle'] = {}
 95     data['last'] = {}
 96
 97 def store(data, full_name):
 98     names = full_name.split()
100     if len(names) == 2: names.insert(1, '')
101     labels = 'first', 'middle', 'last'
103     for label, name in zip(labels, names):
104         people = lookup(data, label, name)
105     if people:
106         people.append(full_name)
107     else:
108         data[label][name] = [full_name]
109
110 def lookup(data, label, name):
111     return data[label].get(name)
112
113
114 MyNames = {}
115 init(MyNames)
116 store(MyNames, 'John Larry Smith')
117 lookup(MyNames, 'middle', 'Smith')

If it tells you so I'm not really sure its a good book - partially for
teaching you into the unpythonic way to do things (above stuff, if its
not a counter example, should really go into a class)

Have you tried the tutorial first? Its online and very easy to follow
from the very beginning but you can also skip parts if you are sure you
already understand it:

http://docs.python.org/tutorial/

HTH
Tino

The book is "Apress Beginning Python 2nd Edition". I think what you
are saying is if I don't understand all of the code I should go into a
class? Unfortunately I don't have the money or time to enroll into a
class and even if I did they wouldn't be teaching Python it would be
Java instead...and I've already taken Java before...so that's not
really an option...

Regardless, I understand up to the part "for label, name in zip
(labels, names):" which zips the two sequences 'names' and 'labels'
into a list of tuples...

What I am not totally sure about is when the store function callsthe
lookup function and does "return data[label].get(name)", that line
"trips" me up some....then the lookup function returns that back to
the store function, assigns the data to the variable 'people', THEN
does this, which also isn't that clear to me what it's all doing:

if people:
people.append(full_name)
else:
data[label][name] = [full_name]

My main problem is finding out what's it's actually *doing*? I know
and understand the terminologies (what 'append' does, what a
'sequence' is, a 'list', a 'tuple', 'if'...'else'...etc...et....)

Thanks for the reply back
 
D

david wright

----- Original Message ----

From: j <[email protected]>
To: (e-mail address removed)
Sent: Mon, November 23, 2009 10:26:42 AM
Subject: Re: Beginning Question about Python functions, parameters...

astral orange schrieb:


Hi, I am trying to teach myself Python and have a good book to help me
but I am stuck on something and I would like for someone to explain
the following piece of code for me and what it's actually doing.
Certain parts are very clear but once it enters the "def store(data,
full_name): ...." function and the "def lookup()..." function things
get a little confusing for me. Specifically, lines 103-108 *and* Lines
110-111.
Lastly, I am not sure how to print the results I've put into this
program either, the book I'm reading doesn't tell me. As you can tell,
I am a beginner and I don't truly understand everything that is going
on here...a lot, but not all....
Here is the code:
92 def init(data):
93 data['first'] = {}
94 data['middle'] = {}
95 data['last'] = {}
96
97 def store(data, full_name):
98 names = full_name.split()
100 if len(names) == 2: names.insert(1, '')
101 labels = 'first', 'middle', 'last'
103 for label, name in zip(labels, names):
104 people = lookup(data, label, name)
105 if people:
106 people.append(full_name)
107 else:
108 data[label][name] = [full_name]
109
110 def lookup(data, label, name):
111 return data[label].get(name)
112
113
114 MyNames = {}
115 init(MyNames)
116 store(MyNames, 'John Larry Smith')
117 lookup(MyNames, 'middle', 'Smith')

If it tells you so I'm not really sure its a good book - partially for
teaching you into the unpythonic way to do things (above stuff, if its
not a counter example, should really go into a class)

Have you tried the tutorial first? Its online and very easy to follow
from the very beginning but you can also skip parts if you are sure you
already understand it:

http://docs.python.org/tutorial/

HTH
Tino

open it up in IDLE (or whatever development environment you use) and use the debugger to step through the code.

the only way to learn stuff is to actually play with it.

make a guess as to what will happen, run it, did that happen? what did happen? change something, what happens now? etc.
 
M

MRAB

j said:
astral orange schrieb:


Hi, I am trying to teach myself Python and have a good book to help me
but I am stuck on something and I would like for someone to explain
the following piece of code for me and what it's actually doing.
Certain parts are very clear but once it enters the "def store(data,
full_name): ...." function and the "def lookup()..." function things
get a little confusing for me. Specifically, lines 103-108 *and* Lines
110-111.
Lastly, I am not sure how to print the results I've put into this
program either, the book I'm reading doesn't tell me. As you can tell,
I am a beginner and I don't truly understand everything that is going
on here...a lot, but not all....
Here is the code:
92 def init(data):
93 data['first'] = {}
94 data['middle'] = {}
95 data['last'] = {}
96
97 def store(data, full_name):
98 names = full_name.split()
100 if len(names) == 2: names.insert(1, '')
101 labels = 'first', 'middle', 'last'
103 for label, name in zip(labels, names):
104 people = lookup(data, label, name)
105 if people:
106 people.append(full_name)
107 else:
108 data[label][name] = [full_name]
109
110 def lookup(data, label, name):
111 return data[label].get(name)
112
113
114 MyNames = {}
115 init(MyNames)
116 store(MyNames, 'John Larry Smith')
117 lookup(MyNames, 'middle', 'Smith')
If it tells you so I'm not really sure its a good book - partially for
teaching you into the unpythonic way to do things (above stuff, if its
not a counter example, should really go into a class)

Have you tried the tutorial first? Its online and very easy to follow
from the very beginning but you can also skip parts if you are sure you
already understand it:

http://docs.python.org/tutorial/

HTH
Tino

The book is "Apress Beginning Python 2nd Edition". I think what you
are saying is if I don't understand all of the code I should go into a
class? Unfortunately I don't have the money or time to enroll into a
class and even if I did they wouldn't be teaching Python it would be
Java instead...and I've already taken Java before...so that's not
really an option...
[snip]
No, he's saying that the _functions_ shown in the code should go into a
class, but the main criticism is that judging by the code shown above it
doesn't look like a good book, and you should look at the on-line
tutorial first if you haven't already done so.
 
A

astral orange

astral said:
Hi, I am trying to teach myself Python and have a good book to help me
but I am stuck on something and I would like for someone to explain
the following piece of code for me and what it's actually doing.
Certain parts are very clear but once it enters the "def store(data,
full_name): ...." function and the "def lookup()..." function things
get a little confusing for me. Specifically, lines 103-108 *and* Lines
110-111.
Lastly, I am not sure how to print the results I've put into this
program either, the book I'm reading doesn't tell me. As you can tell,
I am a beginner and I don't truly understand everything that is going
on here...a lot, but not all....
Here is the code:
 92 def init(data):
 93     data['first'] = {}
 94     data['middle'] = {}
 95     data['last'] = {}
 96
 97 def store(data, full_name):
 98     names = full_name.split()
100     if len(names) == 2: names.insert(1, '')
101     labels = 'first', 'middle', 'last'
103     for label, name in zip(labels, names):

The zip-function takes n iterables, and produces a list with n-tuples out of
it. Type this into the python-prompt:
zip([1, 2, 3], ["a", "b", "c"])

The other thing here is tuple-unpacking. If you know that something has a
specific length, you can unpack it into distinct values like this:

20

Now

 for label, name in zip(labels, names):

does

 - create a list of tuples, each tuple having two elements, the first being
the label, the second a name
 - loops over this list
 - for each item in the list (remember, it's a 2-tuple!), unpack it into
label and name
104         people = lookup(data, label, name)
105     if people:
106         people.append(full_name)
107     else:
108         data[label][name] = [full_name]
109
110 def lookup(data, label, name):
111     return data[label].get(name)

Data here is expected to be a dictionary of dictionaries. The first level of
keys are the labels. The second is the name. It is expected that labels
always exist, but names might be empty, so instead of writing

  return data[label][name]

it uses get(name) on a dict which will return the  value for the key, or
None:



That being said, I agree with Neo that this introduction seems to be rather
bad.

Diez

Thanks all for the replies back! I do appreciate it.

Yes, lines 104-111 is really where my problem lies in understanding
what is going on here.
I am beginner so this stuff seems a little unwieldy at the moment. :)
I *did* invest $40
into this book so it' what I have to work with. By the way, the book
is, "Apress Beginning Python 2nd Edition"....

But back to the example, on line 104 I see there's a call to the
lookup function, passing 3
parameters ('data', which I think is a nested dictionary, label
(first, middle, last) and name).
But I am getting lost on line 111 after the parameters are passed in
to the lookup function. I'm
not exactly sure what it's returning and when it does return, is this
assigned the the variable
'people'? And if so, I'm not sure what 'append(full_name)' does here.
The else statement which assigns
'[full_name]' to 'data[label][name]' is somewhat confusing as I'm
saying to myself where the heck did
'[full_name]' come "into the picture".

If I could understand what's going on with everything in this the rest
of the chapter and the next
should be fairly easy, but I really need to understand this before I
move on. Thanks again for the
replies back. I am looking over your comments right now.

457r0
 
T

Terry Reedy

astral said:
Yes, lines 104-111 is really where my problem lies in understanding
what is going on here.
I am beginner so this stuff seems a little unwieldy at the moment. :)
I *did* invest $40

Water under the bridge. Focus on the future...
into this book so it' what I have to work with. By the way, the book
is, "Apress Beginning Python 2nd Edition"....

The online tutorial is free. Read it along with the book. Two
explanations of a particular point are often better than one, at least
for me.

Now, to where you seem to be stuck. Data is a dict of 3 dicts, one for
each part of a full [Western] name. Each subdict maps pieces of
fullnames to a list of fullnames that contain that piece in the
appropriate position.

This is something like a database of names with 3 fields and an index
for each field pointing to records in the database, except that there is
no database. This is why the structure strikes people as a bit strange.
The records are still there, off in anonymous dataspace, but there is no
way to access them except via the indexes. If init started with
data['names'] = [] # empty list, not dict
and the third line of store were
data['names'].append(names)
then there would be. You might try that as an exercise once you
understand what is already there.

Anyway, you should "print MyNames" (2.x) or "print(MyNames)" (3.x) after
storing the first name so you can see the structure of MyNames. The
tutorial, of course, tells you this. DO read it.

Then add more data and print again to see what changes. For instance,

store(MyNames, 'Susan Smith')
print(MyNames)

Then try several lookups.

store() checks each of the pieces of a name to see whether or not it is
already in the corresponding key dict. This is the "people =" line. The
important point in lookup is that when dict d does not contain key k,
d.get(k) returns None while the usual d[k]raises a KeyError. So lookup()
always return something, even if just None. So 'people' is either None
or an exiting list of names. In the latter case, the current full names
is added to the list. In the former case, the name-piece is associated
with a new list with one item.

If this is still not clear, add print statements or print function
statements at appropriate places inside the code for the store function.
This is how many people clarify thier understanding of a function,
including when debugging.

Good luck.

Terry Jan Reedy
 
A

astral orange

astral said:
Yes, lines 104-111 is really where my problem lies in understanding
what is going on here.
I am beginner so this stuff seems a little unwieldy at the moment. :)
I *did* invest $40

Water under the bridge. Focus on the future...
into this book so it' what I have to work with. By the way, the book
is, "Apress Beginning Python 2nd Edition"....

The online tutorial is free. Read it along with the book. Two
explanations of a particular point are often better than one, at least
for me.

Now, to where you seem to be stuck. Data is a dict of 3 dicts, one for
each part of a full [Western] name. Each subdict maps pieces of
fullnames to a list of fullnames that contain that piece in the
appropriate position.

This is something like a database of names with 3 fields and an index
for each field pointing to records in the database, except that there is
no database. This is why the structure strikes people as a bit strange.
The records are still there, off in anonymous dataspace, but there is no
way to access them except via the indexes. If init started with
     data['names'] = [] # empty list, not dict
and the third line of store were
     data['names'].append(names)
then there would be. You might try that as an exercise once you
understand what is already there.

Anyway, you should "print MyNames" (2.x) or "print(MyNames)" (3.x) after
storing the first name so you can see the structure of MyNames. The
tutorial, of course, tells you this. DO read it.

Then add more data and print again to see what changes. For instance,

store(MyNames, 'Susan Smith')
print(MyNames)

Then try several lookups.

store() checks each of the pieces of a name to see whether or not it is
already in the corresponding key dict. This is the "people =" line. The
important point in lookup is that when dict d does not contain key k,
d.get(k) returns None while the usual d[k]raises a KeyError. So lookup()
always return something, even if just None. So 'people' is either None
or an exiting list of names. In the latter case, the current full names
is added to the list. In the former case, the name-piece is associated
with a new list with one item.

If this is still not clear, add print statements or print function
statements at appropriate places inside the code for the store function.
This is how many people clarify thier understanding of a function,
including when debugging.

Good luck.

Terry Jan Reedy

Wow! First, thanks Terry for the detailed explanation. I'll spend
the rest of the night trying to figure all of this out. :) Also,
thanks to everyone
else that responded as well. I do appreciate you all volunteering your
time to help.
I should of came here sooner.

As far as the program. I did add print statements such as print
(MyNames) and got back:

{'middle': {}, 'last': {'Smith': ['John Larry Smith']}, 'first': {}}

'Smith': ['John Larry Smith'] was in the last key so I will spend some
time figuring
out just why that is the case. I'll spend more time working with the
functions and
hopefully figure this out soon.

Thanks again!

Thanks again for the responses. I'll take all your advice.
 
T

Terry Reedy

astral said:
As far as the program. I did add print statements such as print
(MyNames) and got back:

{'middle': {}, 'last': {'Smith': ['John Larry Smith']}, 'first': {}}

Hmmm, as I understood the code, either that should be ... 'last': {} ...
before the first store(), as you seem to be thinking below, or after the
first store(),

{'middle': {'Larry': ['John Larry Smith'],
'last': {'Smith': ['John Larry Smith'],
'first': {'John' " ['John Larry Smith']}

or the same with [['John','Larry','Smith']] for each entry (do not
remember exactly what was stored. Maybe a typo.

tjr
 
R

r

Hi, I am trying to teach myself Python and have a good book to help me
but I am stuck on something and I would like for someone to explain
the following piece of code for me and what it's actually doing.
Certain parts are very clear but once it enters the "def store(data,
full_name): ...." function and the "def lookup()..." function things
get a little confusing for me. Specifically, lines 103-108 *and* Lines
110-111.

Lastly, I am not sure how to print the results I've put into this
program either, the book I'm reading doesn't tell me. As you can tell,
I am a beginner and I don't truly understand everything that is going
on here...a lot, but not all....

Here is the code:

 92 def init(data):
 93     data['first'] = {}
 94     data['middle'] = {}
 95     data['last'] = {}
 96
 97 def store(data, full_name):
 98     names = full_name.split()
100     if len(names) == 2: names.insert(1, '')
101     labels = 'first', 'middle', 'last'
103     for label, name in zip(labels, names):
104         people = lookup(data, label, name)
105     if people:
106         people.append(full_name)
107     else:
108         data[label][name] = [full_name]
109
110 def lookup(data, label, name):
111     return data[label].get(name)
112
113
114 MyNames = {}
115 init(MyNames)
116 store(MyNames, 'John Larry Smith')
117 lookup(MyNames, 'middle', 'Smith')

This is a horrible example to show noobs. I think the OP could better
understand this as a class EVEN though the OP may or may not know what
a class *is* yet.
def __init__(self, first, middle, last):
self.first = first
self.middle = middle
self.last = last
<__main__.Name instance at 0x029BFD78>


This time we add a __str__ method, the result will speak louder than
words!!
def __init__(self, first, middle, last):
self.first = first
self.middle = middle
self.last = last
def __str__(self):
return '%s %s %s' %(self.first, self.middle, self.last)
Terry J Reedy

See the difference in the print statements. Now lets have some real
fun and access each sub name by index haha!

def __init__(self, first, middle, last):
self.first = first
self.middle = middle
self.last = last
def __str__(self):
return '%s %s %s' %(self.first, self.middle, self.last)
def __len__(self):
return 3
def __getitem__(self, item):
if item == 0:
return self.first
elif item == 1:
return self.middle
elif item == 2:
return self.last
else:
raise IndexError("Index must be in range 0, 2")

name = Name('Joe', 'blow', 'scripter')
name[0] 'Joe'
name[1] 'blow'
name[2] 'scripter'
len(name)
3

WOW, thats more info in a few lines than any tut i ever seen! I wish i
could have seen that in my initial days, could have save some
countless hours of confusion!!! Maybe i am in the wrong line of work?

Should i keep going...?
 
P

Peter Otten

Terry said:
astral said:
As far as the program. I did add print statements such as print
(MyNames) and got back:

{'middle': {}, 'last': {'Smith': ['John Larry Smith']}, 'first': {}}

Hmmm, as I understood the code, either that should be ... 'last': {} ...
before the first store(), as you seem to be thinking below, or after the
first store(),

{'middle': {'Larry': ['John Larry Smith'],
'last': {'Smith': ['John Larry Smith'],
'first': {'John' " ['John Larry Smith']}

or the same with [['John','Larry','Smith']] for each entry (do not
remember exactly what was stored. Maybe a typo.

That's a bug in the store() function

# as posted
def store(data, full_name):
names = full_name.split()
if len(names) == 2: names.insert(1, '')
labels = 'first', 'middle', 'last'
for label, name in zip(labels, names):
people = lookup(data, label, name)
if people:
people.append(full_name)
else:
data[label][name] = [full_name]

# what was probably intended
def store(data, full_name):
names = full_name.split()
if len(names) == 2: names.insert(1, '')
labels = 'first', 'middle', 'last'
for label, name in zip(labels, names):
people = lookup(data, label, name)
if people:
people.append(full_name)
else:
data[label][name] = [full_name]


Peter
 
A

astral orange

Hi, I am trying to teach myself Python and have a good book to help me
but I am stuck on something and I would like for someone to explain
the following piece of code for me and what it's actually doing.
Certain parts are very clear but once it enters the "def store(data,
full_name): ...." function and the "def lookup()..." function things
get a little confusing for me. Specifically, lines 103-108 *and* Lines
110-111.
Lastly, I am not sure how to print the results I've put into this
program either, the book I'm reading doesn't tell me. As you can tell,
I am a beginner and I don't truly understand everything that is going
on here...a lot, but not all....
Here is the code:
 92 def init(data):
 93     data['first'] = {}
 94     data['middle'] = {}
 95     data['last'] = {}
 96
 97 def store(data, full_name):
 98     names = full_name.split()
100     if len(names) == 2: names.insert(1, '')
101     labels = 'first', 'middle', 'last'
103     for label, name in zip(labels, names):
104         people = lookup(data, label, name)
105     if people:
106         people.append(full_name)
107     else:
108         data[label][name] = [full_name]
109
110 def lookup(data, label, name):
111     return data[label].get(name)
112
113
114 MyNames = {}
115 init(MyNames)
116 store(MyNames, 'John Larry Smith')
117 lookup(MyNames, 'middle', 'Smith')

This is a horrible example to show noobs. I think the OP could better
understand this as a class EVEN though the OP may or may not know what
a class *is* yet.

        def __init__(self, first, middle, last):
                self.first = first
                self.middle = middle
                self.last = last

<__main__.Name instance at 0x029BFD78>

This time we add a __str__ method, the result will speak louder than
words!!

        def __init__(self, first, middle, last):
                self.first = first
                self.middle = middle
                self.last = last
        def __str__(self):
                return '%s %s %s' %(self.first, self.middle, self.last)

Terry J Reedy

See the difference in the print statements. Now lets have some real
fun and access each sub name by index haha!

        def __init__(self, first, middle, last):
                self.first = first
                self.middle = middle
                self.last = last
        def __str__(self):
                return '%s %s %s' %(self.first, self.middle, self.last)
        def __len__(self):
                return 3
        def __getitem__(self, item):
                if item == 0:
                        return self.first
                elif item == 1:
                        return self.middle
                elif item == 2:
                        return self.last
                else:
                        raise IndexError("Index must be in range 0, 2")
name = Name('Joe', 'blow', 'scripter')
name[0] 'Joe'
name[1] 'blow'
name[2] 'scripter'
len(name)

3

WOW, thats more info in a few lines than any tut i ever seen! I wish i
could have seen that in my initial days, could have save some
countless hours of confusion!!! Maybe i am in the wrong line of work?

Should i keep going...?

Yeah, I don't think the example in the book is the best for someone
starting out. I still
am "not getting" certain parts of the program so I think I'll move on
in hopes that it will
*not* came back to haunt me and the book (along with the online
tutorial) will help me grab
more of the basics of Python programming.

As for the "class Name():" example above? Even though I haven't seen
exactly what purpose 'self' serves
yet I can follow and understand what is going on very easily, that
helps out tremendously.
Very clearly written...Thank you!

And thanks again to everyone...
 
T

Terry Reedy

Peter said:
Terry Reedy wrote:
remember exactly what was stored. Maybe a typo.

That's a bug in the store() function

# as posted
def store(data, full_name):
names = full_name.split()
if len(names) == 2: names.insert(1, '')
labels = 'first', 'middle', 'last'
for label, name in zip(labels, names):
people = lookup(data, label, name)
if people:
people.append(full_name)
else:
data[label][name] = [full_name]

# what was probably intended
def store(data, full_name):
names = full_name.split()
if len(names) == 2: names.insert(1, '')
labels = 'first', 'middle', 'last'
for label, name in zip(labels, names):
people = lookup(data, label, name)
if people:
people.append(full_name)
else:
data[label][name] = [full_name]

(Note indent error, which I overlooked)
It is a nuisance when people post untested code, without identifying it
as such. Publishing untested but trivial-to-test code like this (one
print statement needed), especially in a book for learners, is really bad.

(I am trying to do better in the book I am working on.)

tjr
 
R

r

As for the "class Name():" example above? Even though I haven't seen
exactly what purpose 'self' serves
yet I can follow and understand what is going on very easily, that
helps out tremendously.
Very clearly written...Thank you!

Yes and this is the stumbling block that almost every tutorial writer
puts before the uninitiated! Simple, Simple examples are the key. The
subject matter of the example should never outshine the subject that
is being taught. Everybody understand what a first, middle, and last
name is! What really ticks me off is when some show-off tut writer
goes off using an internet protocol or mp3 tags example to explain
classes or functions... WHAT!-O

Pssst...tut writers remember this! While you may be an emacs "zen
master" playing key chords that would make most piano virtuosos
jealous, your tutorials are meant for inexperience users. Yes,
exposing your "huge intelligence" to the world may give you warm
fuzzies, but the "shock-and-awe-freak-show" will only be to the
detriment of the very ideas you are attempting to transform into these
minds.
 
B

Bruno Desthuilliers

astral orange a écrit :
(snip)

As for the "class Name():" example above? Even though I haven't seen
exactly what purpose 'self' serves

It's a reference to the current Name instance. But while technically
correct, I'm sure such this kind of explanation really helps :-/
 
L

Lie Ryan

astral said:
As for the "class Name():" example above? Even though I haven't seen
exactly what purpose 'self' serves

In many other programming language, self (or this, or Me) refers the the
current class instance. In some languages, you can refer to an instance
attribute without an explicit self, this, or Me; the name resolver will
search in the local namespace (method-level), instance namespace
(instance-level), class namespace (class-level), perhaps module level
namespace (file-level), and finally global (application level).

Python interpreter is simple and stupid. It doesn't have many smarts;
instead of having such a sophisticated name resolver, the compiler
passes an argument to the function, making `self` a local variable that
refers to the current instance.

Python programmers accesses instance and class namespace by explicitly
referring to `self`; the name resolver only have two places to lookup
names: local namespace (method level) and global namespace (module-level
[!] not application level in python).

This choice of design simplifies the name resolver, simplifies
method/function object design (since it does not need any code to handle
an otherwise implicit self), and completely eliminates ambiguity (to the
programmer) when having a local variable with the same name as an
instance variable. Among many other advantages.

The side-effect of this design choice is self must be explicitly
referenced to access class/instance attributes; unlike in some other
language where self/this/Me may be omitted when it doesn't clash with
other variable in local namespace.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top