[Tutor] more scraping and saving

2011-01-03 Thread Tommy Kaas
Hi - I was helped the other day in an attempt to scrape and save a simple
web page. I'm using what I learned and trying another. It should be very
simple, but I only get the first row of names saved.

Can anybody help with an explanation?

 

(It's a public list of names of doctors with knows connections to the
farmaceutical industry).

This time I try to start at the right table (the third on the page) by using
the class attribute. Does that make sense?

Thanks in advance - here is the code:

 

import urllib2 

from BeautifulSoup import BeautifulSoup

 

 

import codecs

 

f = codecs.open("laeger.txt", "w", encoding="Latin-1")

 

 

soup =
BeautifulSoup(urllib2.urlopen('http://www.laegemiddelstyrelsen.dk/include/88
06/tilladelse_laeger.asp').read())

 

for row in soup('table', {'class' : 'tableLeftRight3030'}):

tds = row('td')

 

output = ";".join(tds[i].string for i in (0, 1, 2, 3, 4))

f.write(output + '\n')

f.close()

 

 

Tommy Kaas

 

Kaas & Mulvad

Lykkesholms Alle 2A, 3.

1902 Frederiksberg C

 

Mobil: 27268818

Mail:   tommy.k...@kaasogmulvad.dk

Web:   www.kaasogmulvad.dk

 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How does it work?

2011-01-03 Thread Neo Vector
Hi All,
Could you explain me how does it work, pls?
==
>>>r = ''
>>>for c in 'abcd':
r = c + r
...
...
>>>r
'dcba'
==
Best Regards,
Neo Vector



  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How does it work?

2011-01-03 Thread Shrivats
On Mon, Jan 03, 2011 at 10:52:26PM +0800, Neo Vector wrote:
> Hi All,
Hello, 
> Could you explain me how does it work, pls?

Sure, I'm not telling you how that works. However, I'll alter your code snippet
a little bit and see if you can understand after that. 
> ==
> >>>r = '1'
> >>>for c in 'abcd':
  print r
> r = c + r
> ...
> ...
1
a1
ba1
cba1
> >>>r
> 'dcba1'
> ==

Let me know if you still face problems. 

HTH,

Shrivats
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How does it work?

2011-01-03 Thread Shrivats
On Mon, Jan 03, 2011 at 08:32:18PM +0530, Shrivats wrote:
> On Mon, Jan 03, 2011 at 10:52:26PM +0800, Neo Vector wrote:
> > Hi All,
> Hello, 
> > Could you explain me how does it work, pls?
> 
> Sure, I'm not telling you how that works. However, I'll alter your code 
> snippet
> a little bit and see if you can understand after that. 
> > ==
> > >>>r = '1'
> > >>>for c in 'abcd':
>   print r
> > r = c + r
> > ...
> > ...
> 1
> a1
> ba1
> cba1
> > >>>r
> > 'dcba1'
> > ==
> 
> Let me know if you still face problems. 
Oh, and for more information - 
http://docs.python.org/tutorial/introduction.html#strings
http://docs.python.org/tutorial/controlflow.html#for-statements

Specifically, the idea behind this is, Strings are basically a list of
characters. So they can be treated as iterable collections. :)
> 
> HTH,
> 
> Shrivats
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How does it work?

2011-01-03 Thread Alan Gauld
"Neo Vector"  wrote 


Could you explain me how does it work, pls?
==

r = ''


r is an empty string


for c in 'abcd':


c takes the value of each letter in turn


   r = c + r


strings can be added such that the result is the 
concatenation of the two strings. So in this case:

r becomes the sum of its old value and the current value of c

repeat for the next value of c.

If that doesn't help then tell us which bit(s) of it you 
don't understand.


HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How does it work?

2011-01-03 Thread Patty


- Original Message - 
From: "Patty" 

To: "Alan Gauld" 
Sent: Monday, January 03, 2011 9:05 AM
Subject: Re: [Tutor] How does it work?


Hi Folks - I read this code and tried to parse it as a pop quiz for myself 
;) and have a question, maybe 2 clarifications,  below:


- Original Message - 
From: "Alan Gauld" 

To: 
Sent: Monday, January 03, 2011 8:09 AM
Subject: Re: [Tutor] How does it work?



"Neo Vector"  wrote

Could you explain me how does it work, pls?
==

r = ''


r is an empty string


for c in 'abcd':


c takes the value of each letter in turn


   r = c + r


When I first looked at this - I thought that the variable 'c' would have 
had to be initialized
first earlier in the program.  And I thought that the programmer would 
input a single char or a single space.   I wasn't thinking counting 
variable for some reason.  So is 'for c in', one or more of key words that 
Python understands that a loop is here and to actually trigger counting in 
a loop? Does it start with a 1 or 0 internally to do this?


I also realized a mistake I may have made - maybe I confused 'for c in' 
with 'while c in'.


r=''
c="d"
while c in 'abcd':
  r=c+r

   Or

r=''
c="d"
while c in ['a', 'b', 'c', 'd']:
  r=c+r

Also for myself I think I would have used different descriptive names for 
variables so that would have been less likely to throw myself off.  And 
also doing this fast to see if I have learned.


I really feel comfortable with Python now after six months and my small 
application is completed and looks really good.   I don't know how I would 
have been able to make the simplest, smallest GUI part of my application - 
using Tkinter and PIL- fast without the references and explanations of 
Wayne Werner and Alan -  Thanks to those on the list who are so helpful!


Patty




strings can be added such that the result is the concatenation of the two 
strings. So in this case:

r becomes the sum of its old value and the current value of c

repeat for the next value of c.

If that doesn't help then tell us which bit(s) of it you don't 
understand.


HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor






___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How does it work?

2011-01-03 Thread Dave Angel

On 01/-10/-28163 02:59 PM, Patty wrote:



for c in 'abcd':


..

When I first looked at this - I thought that the variable 'c' would
have had to be initialized
first earlier in the program. And I thought that the programmer would
input a single char or a single space. I wasn't thinking counting
variable for some reason. So is 'for c in', one or more of key words
that Python understands that a loop is here and to actually trigger
counting in a loop? Does it start with a 1 or 0 internally to do this?



There's not necessarily any integer indexing going on.  for xxx in yyy
is a specific syntax that specifies a loop based on a sequence.  In this 
case the string 'abcd' is a sequence of chars, so you get c to have a 
value of 'a',  'b',  'c', and 'd'.  But other sequences might not have 
any index meaning at all, so it doesn't make sense to ask if it's 0 or 1 
based.  For example, you can iterate over the keys of a map, where the 
order is irrelevant.  All you really know is you'll get them all if you 
finish the loop.



I also realized a mistake I may have made - maybe I confused 'for c
in' with 'while c in'.

r=''
c="d"
while c in 'abcd':
r=c+r



You messed up the indentation.  But if the r=c+r line is indented, then 
this is an infinite loop.  It'll quit when memory is exhausted.  Why? 
Because nothing in the loop changes c.  So since it's in the sequence at 
the beginning, it will always be.



Or

r=''
c="d"
while c in ['a', 'b', 'c', 'd']:
r=c+r



Similarly here.


Also for myself I think I would have used different descriptive names
for variables so that would have been less likely to throw myself off.


Good idea.


And also doing this fast to see if I have learned.

I really feel comfortable with Python now after six months and my
small application is completed and looks really good. I don't know how
I would have been able to make the simplest, smallest GUI part of my
application - using Tkinter and PIL- fast without the references and
explanations of Wayne Werner and Alan - Thanks to those on the list
who are so helpful!

Patty



HTH

DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How does it work?

2011-01-03 Thread Alan Gauld


"Patty"  wrote


for c in 'abcd':



c takes the value of each letter in turn


When I first looked at this - I thought that the variable 'c' would 
have had to be initialized first earlier in the program.


It is initialized earluier - in the for statement, each time through 
the

loop it gets reinitialized to a new value.

... I wasn't thinking counting variable for some reason.  So is 
'for c in', one or more of key words that Python understands that a 
loop is here and to actually trigger counting in a loop? Does it 
start with a 1 or 0 internally to do this?


In the case of a for loop it doesn't count as such.
It takes each value from a sequience and applies it to the
loop variable. Personally I think it wouyld have read better
if they called it "foreach" so your loop would look like

foreach char in 'abcd':

or

foreach item in [1,2,3,4]:

etc...

But they didn't so we are stuck with for.

I also realized a mistake I may have made - maybe I confused 'for c 
in'



while c in 'abcd':


This is completely different.
In this case we can clarify it by adding some parentheses:

while (c in 'abcd'):

the test is all of the bit in parens. And the test is a test of 
whether

c is in the string or not. Python does not modify the variable 'c' in
this case, that only happens with a for loop.

You can read more about the various python loop structures
in the loops topic of my tutorial.


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How does it work?

2011-01-03 Thread Patty
Yes, I knew there was something I wasn't getting.  This is the explanation I 
was looking for - and I'm sorry about the incorrect indentation.  And I 
agree with Alan that 'foreach' would have been a good name for this type of 
loop.   I need to sort out 'loop structures' in my notes and read up on 
these for sure.



Thanks,

Patty

- Original Message - 
From: "Dave Angel" 

To: "Patty" 
Cc: 
Sent: Monday, January 03, 2011 9:52 AM
Subject: Re: [Tutor] How does it work?



On 01/-10/-28163 02:59 PM, Patty wrote:



for c in 'abcd':


..

When I first looked at this - I thought that the variable 'c' would
have had to be initialized
first earlier in the program. And I thought that the programmer would
input a single char or a single space. I wasn't thinking counting
variable for some reason. So is 'for c in', one or more of key words
that Python understands that a loop is here and to actually trigger
counting in a loop? Does it start with a 1 or 0 internally to do this?



There's not necessarily any integer indexing going on.  for xxx in yyy
is a specific syntax that specifies a loop based on a sequence.  In this 
case the string 'abcd' is a sequence of chars, so you get c to have a 
value of 'a',  'b',  'c', and 'd'.  But other sequences might not have any 
index meaning at all, so it doesn't make sense to ask if it's 0 or 1 
based.  For example, you can iterate over the keys of a map, where the 
order is irrelevant.  All you really know is you'll get them all if you 
finish the loop.



I also realized a mistake I may have made - maybe I confused 'for c
in' with 'while c in'.

r=''
c="d"
while c in 'abcd':
r=c+r



You messed up the indentation.  But if the r=c+r line is indented, then 
this is an infinite loop.  It'll quit when memory is exhausted.  Why? 
Because nothing in the loop changes c.  So since it's in the sequence at 
the beginning, it will always be.



Or

r=''
c="d"
while c in ['a', 'b', 'c', 'd']:
r=c+r



Similarly here.


Also for myself I think I would have used different descriptive names
for variables so that would have been less likely to throw myself off.


Good idea.


And also doing this fast to see if I have learned.

I really feel comfortable with Python now after six months and my
small application is completed and looks really good. I don't know how
I would have been able to make the simplest, smallest GUI part of my
application - using Tkinter and PIL- fast without the references and
explanations of Wayne Werner and Alan - Thanks to those on the list
who are so helpful!

Patty



HTH

DaveA




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] matplotlib.pylab.plotfile formatting help

2011-01-03 Thread Sean Carolan
I've got a csv file that contains two data fields, the short name of a
month and an integer.  I'm experimenting with pylab and ipython to get
a feel for how pylab works.  I'm able to generate a bar graph from my
data, but there are two problems with it:

1.  I don't want "2011" appended to the month names.  This data is
from 2010, and I only want the short month name under each bar.
2.  The bars are very narrow and I'm not sure how to widen them.

Here's my CSV data, stored in a file called csvdata.csv:

month,systems
Jan,17
Feb,49
Mar,77
Apr,59
May,42
Jun,137
Jul,102
Aug,115
Sep,57
Oct,134
Nov,131
Dec,197

And here's the "ipython -pylab" command that I'm using to generate the graph:

plotfile('csvdata.csv', ('month', 'systems'), plotfuncs={'systems': 'bar'},)

I've read through some of the documentation for matplotlib, but having
never used matlab or pylab before today it's a bit confusing.  Does
anyone know how to solve #1 and #2 above?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Initialize values from a text input file

2011-01-03 Thread Tim Johnson
I'm just have a little fun here, but I bet that comments will help
further elighten me on the subtleties of python.

consider the following console session:
>>> L = ['foo','bar']
>>> locals()[L[0]] = L[1]
>>> foo
'bar'
>>> 'foobar' in locals()
False
>>> 'foo' in locals()
True
>>> locals()
{'__builtins__': , 'L': ['foo',
'bar'], '__package__': None, '__name__': '__main__', 'foo': 'bar',
'__doc__': None}

Given that I have a text file as input with names and values
with a seperator (TAB, for instance)
I could initialize variables in a local scope, or I could build a
dictionary. Actually the dictionary is preferable for the targeted
application.

However, for the sake of edification, I would welcome comments on
the session above, and let's pretend that `L' is the result of a
line read from a file and split on '\t'.
TIA
tim
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Initialize values from a text input file

2011-01-03 Thread Alan Gauld


"Tim Johnson"  wrote


consider the following console session:

L = ['foo','bar']
locals()[L[0]] = L[1]
foo

'bar'

locals()

{'__builtins__': , 'L': ['foo',
'bar'], '__package__': None, '__name__': '__main__', 'foo': 'bar',
'__doc__': None}

I could initialize variables in a local scope, or I could build a
dictionary. Actually the dictionary is preferable for the targeted
application.


Except in extreme cases I'd say a dictionary was better in 
almost any situation. Messing with locals() is a dodgy business 
at best, and can lead to debugging insanity at worst, its better 
to keep externally initialized data explicit in almost every case.



However, for the sake of edification, I would welcome comments on
the session above, and let's pretend that `L' is the result of a
line read from a file and split on '\t'.


My only comment: Don't go there... creating random variables 
in your namespace that don't actually appear in your code makes 
using global variables seem positively benign.


Once you create them what are you going to do? 
Litter your code with


try:
doSomething(withNameThatMightExist)
except NameError:
doSomethingElse()

It is a minefield just waiting to suck you in.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Initialize values from a text input file

2011-01-03 Thread Steven D'Aprano

Tim Johnson wrote:

I'm just have a little fun here, but I bet that comments will help
further elighten me on the subtleties of python.

consider the following console session:

L = ['foo','bar']
locals()[L[0]] = L[1]


This will not do what you think it does. In general, local variables are 
not writable except the normal way by `name = value` assignment. Try 
this function:


def spam():
x = 1
print(x)
locals()['x'] = 2
print(x)


The fact that assignment to locals() works in the top-level global scope 
is an accident of implementation.





foo

'bar'

'foobar' in locals()

False

'foo' in locals()

True

locals()

{'__builtins__': , 'L': ['foo',
'bar'], '__package__': None, '__name__': '__main__', 'foo': 'bar',
'__doc__': None}

Given that I have a text file as input with names and values
with a seperator (TAB, for instance)
I could initialize variables in a local scope, or I could build a
dictionary. Actually the dictionary is preferable for the targeted
application.


Have you considered using the ConfigParser module?



However, for the sake of edification, I would welcome comments on
the session above, and let's pretend that `L' is the result of a
line read from a file and split on '\t'.


(1) This won't work except in the global scope.

(2) Even if it did work, do you trust the source of the text? Taking 
external data provided by arbitrary untrusted users and turning it into 
variables is a good way to have your computer owned by bad guys. This 
technique would make your software vulnerable to code injection attacks. 
You *might* be safe, if you never eval() or exec() the strings coming 
out of the file. But I wouldn't bet the security of my application on 
that -- especially if it were running in a web browser or on a server.


Actually, no, that's wrong -- even if you never use eval() or exec(), 
you're still vulnerable to Denial Of Service attacks if the attacker can 
put junk you don't expect into the file. Something as trivial as:


number = abc

in the input file could crash your application, if you aren't performing 
sufficient data validation when you use "number". Or they can shadow 
builtins and stop your code from working:


len = 123
# later...
len(some_list)  # this will fail

This isn't a theoretical threat, something like 3 or 4 out of 5 security 
vulnerabilities these days are code injection attacks, and there are a 
LOT of security vulnerabilities. (The majority of these are SQL injections.)


At the very least, you should pass the items through a white list of 
allowed variable names, and validate the values. Do not use a black list 
of forbidden variables! The problem with the black list idea is that it 
assumes that you can think of every possible vulnerability ahead of 
time. You can't.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Initialize values from a text input file

2011-01-03 Thread Tim Johnson
* Steven D'Aprano  [110103 15:03]:
> Tim Johnson wrote:
>> I'm just have a little fun here, but I bet that comments will help
>> further elighten me on the subtleties of python.
>>
>> consider the following console session:
> L = ['foo','bar']
> locals()[L[0]] = L[1]
>
> This will not do what you think it does. In general, local variables are  
> not writable except the normal way by `name = value` assignment. Try  
> this function:
>
> def spam():
> x = 1
> print(x)
> locals()['x'] = 2
> print(x)
>
>
> The fact that assignment to locals() works in the top-level global scope  
> is an accident of implementation.
 :) thanks for doing my homework for me.
>
> Have you considered using the ConfigParser module?
 Good tip. I will look at it

> (1) This won't work except in the global scope.
>
> (2) Even if it did work, do you trust the source of the text? Taking  
> external data provided by arbitrary untrusted users and turning it into  
> variables is a good way to have your computer owned by bad guys. 
  Say what? I'm not talking about anything accessible by "arbitrary
  users". Sorry if I gave that impression!
  Thanks
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Initialize values from a text input file

2011-01-03 Thread Tim Johnson
* Alan Gauld  [110103 14:47]:
>
> "Tim Johnson"  wrote
>
>> consider the following console session:
> L = ['foo','bar']
> locals()[L[0]] = L[1]
> foo
>> 'bar'
> locals()
>> {'__builtins__': , 'L': ['foo',
>> 'bar'], '__package__': None, '__name__': '__main__', 'foo': 'bar',
>> '__doc__': None}
>>
>> I could initialize variables in a local scope, or I could build a
>> dictionary. Actually the dictionary is preferable for the targeted
>> application.
  Actually, the dictionary is the target medium

> Except in extreme cases I'd say a dictionary was better in almost any 
> situation. Messing with locals() is a dodgy business at best, and can 
> lead to debugging insanity at worst, its better to keep externally 
> initialized data explicit in almost every case.
  I agree, that's why I said I "was having a little fun".
  Now, Alan, do you know anything about PHP? If you do, can you
  comment on the PHP extract() function?
  thanks
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] subclass not inheriting attributes?

2011-01-03 Thread Alex Hall
Hi all,
I have a solitaire game in which I use a "Pile" class. This class is
meant to hold a bunch of cards, so I subclass it for the deck, the ace
stacks, and the seven main stacks, defining rules and methods for each
but also relying on the parent Pile class's methods and attributes.
However, I keep getting an error that an attribute in the parent does
not exist in the child. Below is a simplified example, but it gives me
the exact same error: child object has no attribute l.

class parent(object):
 def __init__(self, l=None):
  if l is None: l=[]

class child(parent):
 def __init__(self, *args, **kwords):
  super(parent, self).__init__(*args, **kwords)
  self.l.append(5)

c=child()
print c.l

Again, I get an error saying that 'child' object has no attribute 'l'.
Python 2.7 on win7x64. Thanks.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Initialize values from a text input file

2011-01-03 Thread Alan Gauld


"Tim Johnson"  wrote


 Now, Alan, do you know anything about PHP? If you do, can you
 comment on the PHP extract() function?


I know enough basic PHP to read a page with code in it and 
get the general drift. I've never written a line of it and have 
learned enough about it that I don't want to! :-)


Now as for extract() - it doesn't appear in my Teach Yourself PHP 
book, so nope, I've no idea what it does, I'd need to look it up.

And I'm way too lazy, and it's way too late to do that! :-)

Alan G.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subclass not inheriting attributes?

2011-01-03 Thread Alan Gauld


"Alex Hall"  wrote


class parent(object):
def __init__(self, l=None):
 if l is None: l=[]


l is a local variable inside init().

You wanted self.l...

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subclass not inheriting attributes?

2011-01-03 Thread Walter Prins
On 4 January 2011 00:47, Alex Hall  wrote:

> class parent(object):
>  def __init__(self, l=None):
>  if l is None: l=[]
>

Missing "self". Perhaps you meant:

class parent(object):
 def __init__(self, l=None):
   if l is None: self.l=[]
   else: self.l=l


Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subclass not inheriting attributes?

2011-01-03 Thread Wayne Werner
On Mon, Jan 3, 2011 at 6:47 PM, Alex Hall  wrote:

> Hi all,
> I have a solitaire game in which I use a "Pile" class. This class is
> meant to hold a bunch of cards, so I subclass it for the deck, the ace
> stacks, and the seven main stacks, defining rules and methods for each
> but also relying on the parent Pile class's methods and attributes.
> However, I keep getting an error that an attribute in the parent does
> not exist in the child. Below is a simplified example, but it gives me
> the exact same error: child object has no attribute l.
>
> class parent(object):
>  def __init__(self, l=None):
>  if l is None: l=[]
>
> class child(parent):
>  def __init__(self, *args, **kwords):
>  super(parent, self).__init__(*args, **kwords)
>  self.l.append(5)
>
> c=child()
> print c.l
>
> Again, I get an error saying that 'child' object has no attribute 'l'.
> Python 2.7 on win7x64. Thanks.


Try

p = parent()
p.l

Does that do what you expected?

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subclass not inheriting attributes?

2011-01-03 Thread Vern Ceder
On Mon, Jan 3, 2011 at 7:47 PM, Alex Hall  wrote:

> Hi all,
> I have a solitaire game in which I use a "Pile" class. This class is
> meant to hold a bunch of cards, so I subclass it for the deck, the ace
> stacks, and the seven main stacks, defining rules and methods for each
> but also relying on the parent Pile class's methods and attributes.
> However, I keep getting an error that an attribute in the parent does
> not exist in the child. Below is a simplified example, but it gives me
> the exact same error: child object has no attribute l.
>
> class parent(object):
>  def __init__(self, l=None):
>  if l is None: l=[]
>
> class child(parent):
>  def __init__(self, *args, **kwords):
>  super(parent, self).__init__(*args, **kwords)
>

I believe you need to pass the object both to super() and to the method
itself, as in:

super(parent, self).__init__(self, *args, **kwords)

See the example at
http://docs.python.org/library/functions.html?highlight=super#super

HTH,

Vern


>  self.l.append(5)
>
> c=child()
> print c.l
>
> Again, I get an error saying that 'child' object has no attribute 'l'.
> Python 2.7 on win7x64. Thanks.
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehg...@gmail.com; http://www.facebook.com/mehgcap
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Vern Ceder
vce...@gmail.com, vce...@dogsinmotion.com
The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subclass not inheriting attributes?

2011-01-03 Thread Alex Hall
On 1/3/11, Wayne Werner  wrote:
> On Mon, Jan 3, 2011 at 6:47 PM, Alex Hall  wrote:
>
>> Hi all,
>> I have a solitaire game in which I use a "Pile" class. This class is
>> meant to hold a bunch of cards, so I subclass it for the deck, the ace
>> stacks, and the seven main stacks, defining rules and methods for each
>> but also relying on the parent Pile class's methods and attributes.
>> However, I keep getting an error that an attribute in the parent does
>> not exist in the child. Below is a simplified example, but it gives me
>> the exact same error: child object has no attribute l.
>>
>> class parent(object):
>>  def __init__(self, l=None):
>>  if l is None: l=[]
Walter was right, and I changed it to
  if l is None: self.l=[]
  else: self.l=l
It did not get rid of the error, though.
>>
>> class child(parent):
>>  def __init__(self, *args, **kwords):
>>  super(parent, self).__init__(*args, **kwords)
>>  self.l.append(5)
>>
>> c=child()
>> print c.l
>>
>> Again, I get an error saying that 'child' object has no attribute 'l'.
>> Python 2.7 on win7x64. Thanks.
>
>
> Try
>
> p = parent()
> p.l
>
> Does that do what you expected?
Yes, I get [], just as I should. So the question is: if the parent
class is working, why would a class that inherits it not have the l
attribute?
>
> HTH,
> Wayne
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subclass not inheriting attributes?

2011-01-03 Thread Walter Prins
Sorry, my last post was too hasty.  You also had a problem calling super.
It should be like this:

class parent(object):
 def __init__(self, l=None):
   if l is None: self.l=[]
   else: self.l=l

class child(parent):
 def __init__(self, *args, **kwords):
   super(child, self).__init__(*args, **kwords)
   self.l.append(5)

c=child()
print c.l

Basically: In Python 2.x "super()" doesn't know what the current class is.
You have to tell it, as the first parameter.  If you tell it a lie, strange
things will happen.  That's basically what you did.  You called
super(parent,...) instead of super(child,...)

Have a good 2011... ;)

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subclass not inheriting attributes?

2011-01-03 Thread Alex Hall
On 1/3/11, Walter Prins  wrote:
> Sorry, my last post was too hasty.  You also had a problem calling super.
> It should be like this:
>
> class parent(object):
>  def __init__(self, l=None):
>if l is None: self.l=[]
>else: self.l=l
>
> class child(parent):
>  def __init__(self, *args, **kwords):
>super(child, self).__init__(*args, **kwords)
>self.l.append(5)
>
> c=child()
> print c.l
>
> Basically: In Python 2.x "super()" doesn't know what the current class is.
> You have to tell it, as the first parameter.  If you tell it a lie, strange
> things will happen.  That's basically what you did.  You called
> super(parent,...) instead of super(child,...)
I see, and this does indeed now work! Thanks!
>
> Have a good 2011... ;)
>
> Walter
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Initialize values from a text input file

2011-01-03 Thread Hugo Arts
On Tue, Jan 4, 2011 at 2:06 AM, Alan Gauld  wrote:
>
> "Tim Johnson"  wrote
>
>>  Now, Alan, do you know anything about PHP? If you do, can you
>>  comment on the PHP extract() function?
>
> I know enough basic PHP to read a page with code in it and get the general
> drift. I've never written a line of it and have learned enough about it that
> I don't want to! :-)
>
> Now as for extract() - it doesn't appear in my Teach Yourself PHP book, so
> nope, I've no idea what it does, I'd need to look it up.
> And I'm way too lazy, and it's way too late to do that! :-)
>

extract takes an array and merges it with the local symbol table.
Essentially the same thing locals() would do if it was actually
writable everywhere (as Steven points out it isn't).

If you ask me, this is an insanely bad idea and I have not a clue as
to why you'd actually want to do this, rather than just work with the
array.

Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subclass not inheriting attributes?

2011-01-03 Thread Walter Prins
On 4 January 2011 01:16, Vern Ceder  wrote:

> I believe you need to pass the object both to super() and to the method
> itself, as in:
>
> super(parent, self).__init__(self, *args, **kwords)
>
> See the example at
> http://docs.python.org/library/functions.html?highlight=super#super
>
> HTH,
>
> Vern
>
>
I've already pointed out that you're supposed to tell super() the *current*
class and Alex has already indicated that it now works for him?  Is there a
problem with everyone on the mailing list receving posts timeously?

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Initialize values from a text input file

2011-01-03 Thread Tim Johnson
* Hugo Arts  [110103 17:12]:
> On Tue, Jan 4, 2011 at 2:06 AM, Alan Gauld  wrote:
> >
> > "Tim Johnson"  wrote
> >
> >>  Now, Alan, do you know anything about PHP? If you do, can you
> >>  comment on the PHP extract() function?
> >
> > I know enough basic PHP to read a page with code in it and get the general
> > drift. I've never written a line of it and have learned enough about it that
> > I don't want to! :-)
> >
> > Now as for extract() - it doesn't appear in my Teach Yourself PHP book, so
> > nope, I've no idea what it does, I'd need to look it up.
> > And I'm way too lazy, and it's way too late to do that! :-)
> >
> 
> extract takes an array and merges it with the local symbol table.
> Essentially the same thing locals() would do if it was actually
> writable everywhere (as Steven points out it isn't).
> 
> If you ask me, this is an insanely bad idea and I have not a clue as
> to why you'd actually want to do this, rather than just work with the
> array.
  I've decided that members of my company (and I punished myself by
  appointing myself) had to learn a little PHP. At least enough to
  persuade a potential client why python would be a better choice.
  I would consider extract() one of those potent arguments as to why to
  use python
  thanks
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor