Re: [Tutor] SOAPPy - server and threading?

2005-04-23 Thread Kent Johnson

Kristian Rink wrote:
HAt the moment, I
am trying to implement a small client/server system that communicate using 
SOAP, and for each client
to connect to the SOAP server (via HTTP) I wanted to run a thread which 
exclusively is responsible
to serve that very client.
My problem is: Currently I create a SOAPServer and make it available using 
serve_forever(). I
want
to put this into several threads, as well
If you want each request to be handled in its own thread, use ThreadingSOAPServer instead of 
SOAPServer. If you want to dedicate a thread to each client, I think you will have to run multiple 
SOAPServer instances. Each one will need its own port as well.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterator question for a toy class

2005-04-23 Thread Rich Krauter
Marcus Goldfish wrote:
I'm trying to understand custom iterators in Python, and created the
following toy class for sequence comparison, which seems to work:
class Foo(object):
   """A toy class to experiment with __eq__ and __iter__"""
   def __init__(self, listA, listB):
  self.head, self.tail = listA, listB
   def __iter__(self):
  return iter(self.head[:]+self.tail[:])
   def __eq__(self, other):
  """Foo instances are equal if their respective subsequences,
  head, tail, are in the same order"""
  diff = [i for i, j in zip(self, other) if i != j]
  return len(diff) == 0

f1 = Foo( [1,2], ['a','b','c'] )
f2 = Foo( [1,2], ['a','b','c'] )
f3 = Foo( [1,2], ['a','b','d'] )
f1 == f2, f1 == f3
(True, False)
I'm not really sure if I'm implementing iter() correctly, for
instance: should I make copies of the sublists?  Should I try to
implement my own next() method?
Advice, comments, and links to good tutorial web pages on iterators
are appreciated!
Hi Marcus,
Here are some points I noticed -
1) I would probably change your __eq__ method to something like this:
def __eq__(self,other):
   return (self.head,self.tail) == (other.head,other.tail)
2) Or, if you really want your __eq__ method to use the iterator 
returned by __iter__(),

def __eq__(self, other):
for i, j in map(None,self, other):
if i != j:
return False
return True
One reason this might be a little better than your version is that using 
zip() as you have, f1 = Foo( [1,2], ['a','b','c']) and f2 = Foo( [1,2], 
['a','b','c','q'] ) would compare equal. Another reason is that this 
version returns False as soon as it figures out the lists are not equal.

3) It's not a big deal, but instead of what you have in __iter__(), I 
might import itertools and then write something like

def __iter__(self):
return itertools.chain(self.head,self.tail)
4) In this specific case, if you want to use the iterator returned by 
__iter__ in your __eq__ method, I think you should avoid using a next(). 
Here's a silly example why:

class Foo2(object):
   def __init__(self, listA,listB):
  self.head,self.tail = listA,listB
  self._current = -1
  self._cache = None
   def _fill_cache(self):
   """save some state"""
   if not self._cache:
   self._cache = self.head + self.tail
   def __iter__(self):
   """the iterator is the iterable object itself"""
   return self
   def next(self):
   """make the object an iterator"""
   self._fill_cache()
   self._current += 1
   if self._current >= len(self._cache):
   raise StopIteration
   return self._cache[self._current]
   def __eq__(self, other):
   for i, j in map(None,self, other):
   if i != j:
   return False
   return True
if __name__ == '__main__':
f1 = Foo2( [1,2], ['a','b','c'])
f2 = Foo2( [1,2], ['a','b','c'])
f3 = Foo2( [1,2], ['a','b','d'])
print f1 == f2, f1 == f3, f1 == f3 # notice the output here

Good luck.
Rich
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie Question:Regarding Command line Parsing and Run Unix Shell Command

2005-04-23 Thread Max Noel
On Apr 22, 2005, at 21:09, Prasad Kotipalli wrote:
Hello evryone
 I am a newbie to python. I have a makefile which i can compile in
UNIX/LINUX, But i
I am planning to write a python script which actually does what my
MAKEFILE does.
	Then what you want is SCons (http://www.scons.org/). Haven't had the 
occasion to use it yet, but it seems like an instance of Best Thing 
Ever(TM).

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: [Pythonmac-SIG] Re: Weird import problem with PythonIDE on Mac (was 'import problem')

2005-04-23 Thread Just van Rossum
Jack Jansen wrote:

> As always, reading the source provides the answer.
> 
> If you look in PyEdit.py, method Editor.execstring(), you'll see that 
> the only thing "run as __main__" does is set the module name to 
> "__main__". It does *not* change the globals dictionary to __main__.
> 
> I'm not sure about the reasoning behind this, I think Just wanted to 
> make sure that if you had two edit windows open both with "run as 
> __main__" selected they didn't influence each other. On the other hand 
> I can imageine that if you do that, open two windows in __main__ mode, 
> the behaviour you want is exactly that.

It largely as Bob wrote: you can't do this sanely if the script runs in
the same process as the IDE. And what you said: I don't want __main__
scripts to share a namespace. The "Run as __main__" feature is intended
to support the if __name__ == "__main__" idiom, nothing else. Importing
__main__ is a very silly thing to do anyway, if you ask me.

Just
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CLS? (Joseph Quigley)

2005-04-23 Thread Alan Gauld

> In QBASIC there was the command "CLS"
> this wiped the screen and "started printing letters to the screen at
the
> top " of the console window.

This was possible because QBASIC knew what kind of screen it was
working with, Python can't tell that reliably since it runs on
many operating systems.

The best way is probably to use the os.system() call to clear the
screen via the OS. Thus on DOS its

os.system('CLS')

on Linux

os.system('clear')

Failing that you can write a cls function:

def cls():
   print '\n' * 100

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Building application namespaces.

2005-04-23 Thread David Driver
In the root script I import Common. Inside of Common's __init__.py I
import the basic domain modules. Is this correct?


>If I understand the setup correctly it should work. How are you
importing Common? If you say
>import Common
>you should be able to refer to Common.sobjs. If you say
>from Common import *
>then sobjs will be imported into the main module namespace.
>
>Kent
-- 

***
See there, that wasn't so bad.
***
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Tracking URL in browser location bar

2005-04-23 Thread Gautam Saha
Hi:
A newbie here..I was wondering if python can help me to track the URL in
browser (IE6+, FF, Mozilla) location bar.
What I want is to get each URL from the the browser location bar, as 
user clicks from
links to link  in the web (or types an URL) and store it in  a flat file 
and flag some how
the entry page url for all my clicks.
If I open a new page (via a bookmark or type the url) it will then flag 
the 1st page again
and keep a record of all the pages I visits afterwards (so that I can 
create a tree).

1.Can it be done easily?
2. Can it be done for each browser (mainly IE6+, FF, Mozilla) ?
Primarily the program will be sitting in the user's PC (Windows based) 
and keep everything
locally. It would be ideal if it is platform and browser independent.

I really have no clue if we can do this. Any help in the right direction 
or  a general discussion
on a solution is greatly appreciated.

Thanks,
Gautam
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] incomprehension in type of classes.

2005-04-23 Thread Cedric BRINER
> >from (I):
> >
> >class CYear:
> >   def __init__(self, year):
> >  self.__year=year
> >  print str(self.__year) <<---(*)
> >  print 'dir of: '+str(dir(self))
> >  print 'type of: '+str(type(self))
> >   def __str__(self):
> >  return "we are in "+str(self.year)
> >
> >
> >to (IIOB):
> >
> >class CYearDerived(int):
> >   def __init__(self, year):
> >  super(CYearDerived,self).__init__(year)
> >  self.__year=year
> >  print str(self.__year)<<-(*OB)
> >  print 'dir of: '+str( dir(self) )
> >  print 'type of: '+str(type(self))
> >   def __str__(self):
> >  return "we are in "+super(CYearDerived,self).__str__()
> 
> >why type of (CYear(2005))
> >
> >
> >and type(CYearDerived)
> >
> >
> >doesn't give the same type ???
> 
> It's a difference between new-style and old-style classes. CYear is an 
> old-style class because it doesn't inherit from object. CYearDerived is a 
> new-style class because it inherits from int which is a subtype of object:
> 
>  >>> class C: pass # old-style class
>  ...
>  >>> type(C())
> 
>  >>> C().__class__
> 
> 
>  >>> class C2(object): pass # new-style class
>  ...
>  >>> type(C2())
> 
>  >>> C2().__class__
> 
> 
>  >>> int.__bases__ # int inherits from object
> (,)
> 
> I'm not sure *why* there is this difference between the two types of 
> classes, but there is...
ah... I din't know that there was two kinds of classes. So you mean that, 
now the new style object should be like: class A(object): pass

>>> class A: pass
...
>>> class B(object): pass
...
>>> a=A()
>>> b=B()

I see that dir (b) compare to dir(a) provides more stuff. So the new style of a 
class, is not only about syntax but also about properties ???

ok, I'll try to find more about this !

> By the way extending int does not work the way you have done it here. int 
> is an immutable type so you have to initialize it in the __new__() method, 
> not in __init__(). Read the details here:
> http://www.python.org/2.2/descrintro.html#__new__
this link is very usefull

thanks

Cedric BRINER
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterator question for a toy class

2005-04-23 Thread Kent Johnson
Rich Krauter wrote:
2) Or, if you really want your __eq__ method to use the iterator 
returned by __iter__(),

def __eq__(self, other):
for i, j in map(None,self, other):
if i != j:
return False
return True
That's not right either, it will compare Foo([None], []) == Foo([], []) for 
example.
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] incomprehension in type of classes.

2005-04-23 Thread Kent Johnson
Cedric BRINER wrote:
I'm not sure *why* there is this difference between the two types of 
classes, but there is...
ah... I din't know that there was two kinds of classes. So you mean that, now the new style
object should be like: class A(object): pass
Yes, this is the recommended way to define a class since Python 2.2.
ok, I'll try to find more about this !
This document
http://www.python.org/2.2/descrintro.html
and the two PEPs it links to are the best source of information on new-style classes. Another good 
summary is here:
http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SOAPPy - server and threading?

2005-04-23 Thread Kristian Rink

Hi Kent;

On Fri, 22 Apr 2005 10:53:52 -0400
Kent Johnson <[EMAIL PROTECTED]> wrote:

> If you want each request to be handled in its own thread, use
> ThreadingSOAPServer instead of SOAPServer. If you want to dedicate a
> thread to each client, I think you will have to run multiple

Thanks for pointing me the way here... Actually, my current idea is to
run a "master server" which the clients connect to and, while
connecting, get returned a local port number where their "responsible"
SOAP server thread is listening. Anyhow, do you have a short example or
documentation link handy on how to get ThreadedSOAPServer running?
SOAPpy documentation same as googling for it sadly weren't very
extensive on that... :/

Thanks and bye,
Kris
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with this script

2005-04-23 Thread John Carmona
Hi guys, I am back from my hols.
Jacob S gave me this little exercise to do a little while ago.
1) Make a program to compute the areas of several figures. Make it display a 
menu on startup, ask for a choice, and then compute the area of the 
figure chosen by asking for dimensions.

2) Make another script similiar to #1 using volumes instead of areas
I have decided to merge the 2 scripts. First I should have a menu asking me 
if I want to compute areas or volumes. Then depending on the choice it 
should display the relevant menu. My first menu comes on but if I select "b" 
or "c" the script does not run. The error message points out that 
"print_options()" or "print_options_2()" are not defined. Could somebody 
point me into the right direction, thanks.

-
#By J Carmona
#Programme that compute volumes or surfaces
##First menu is for the calculation of area
##Second menu is for the calculation of volume
##First ask the user what he wants to do
running = True
def area_rect():
   length = input("Length: ")
   width = input ("Width: ")
   print "The area is: ",length*width
def area_circ():
   radius = input("What is the radius?: ")
   print "The area is approximately: ", 3.14159*(radius**2)
def area_squ():
   side = input ("What is the length of one side?: ")
   print "The area is: ", side*side
def area_tgle():
   base = input ("What is the base of the triangle?: ")
   heigth = input ("What is the heigth of the triangle?: ")
   print "The area is: ",base*heigth/2
def vol_sph():
   radius = input("What is the radius?: ")
   print "The volume is: ", (4*3.14159*radius**3)/3
def vol_cube():
   side = input("Side: ")
   print "The volume is: ",side**3
def vol_box():
   width = input ("What is the width of the box?: ")
   length = input ("What is the length of the box?: ")
   depth = input ("What is the depth of the box?: ")
   print "The volume is: ", width*length*depth
def vol_cone():
   radius = input ("What is the radiux of the base of the cone?: ")
   heigth = input ("What is the heigth of the cone?: ")
   print "The volume is: ", (1/3)(3.144159*(radius**2))(heigth)
def task_options():
   print "---"
   print "Options:"
   print "a. Print options: "
   print "b. Do you want to calculate areas?: "
   print "c. Do you want to calculate volumes?: "
   print "d. Quit the programme"
   print "---"
   choice = raw_input("Choose an option: ")
   if choice == 'a':
   print task_options()
   elif choice == 'b':
   print print_options()
   elif choice == 'c':
   print print_options_2()
   elif choice == 'd':
   running = False
print task_options()
def print_options():
   print "--"
   print "Options:"
   print "a. print options"
   print "b. calculate circle area"
   print "c. calculate square area"
   print "d. calculate rectangle area"
   print "e. calculate triangle area"
   print "f. quit the programme"
   print "--"
   choice = raw_input("Choose an option: ")
   if choice == 'a':
   print_options()
   elif choice == 'b':
   area_circ()
   elif choice == 'c':
   area_squ()
   elif choice == 'd':
   area_rect()
   elif choice == 'e':
   area_tgle()
   elif choice == 'f':
   print_options()
#Call starting menu
print_options()
def print_options_2():
   print "--"
   print "Options:"
   print "a. print options"
   print "b. calculate the volume of a sphere"
   print "c. calculate the volume of a cube"
   print "d. calculate the volume of a box"
   print "e. calculate the volume of a cone"
   print "f. quit the programme"
   print "--"
   choice = raw_input("Choose an option: ")
   if choice == 'a':
   print_options()
   elif choice == 'b':
   vol_sph()
   elif choice == 'c':
   vol_cube()
   elif choice == 'd':
   vol_box()
   elif choice == 'e':
   vol_cone()
   elif choice == 'e':
   print_options()
#Call starting menu
print_options()
---
JC
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SOAPPy - server and threading?

2005-04-23 Thread Kent Johnson
Kristian Rink wrote:
Hi Kent;
On Fri, 22 Apr 2005 10:53:52 -0400
Kent Johnson <[EMAIL PROTECTED]> wrote:

If you want each request to be handled in its own thread, use
ThreadingSOAPServer instead of SOAPServer. If you want to dedicate a
thread to each client, I think you will have to run multiple

Thanks for pointing me the way here... Actually, my current idea is to
run a "master server" which the clients connect to and, while
connecting, get returned a local port number where their "responsible"
SOAP server thread is listening.
Yes, that is the usual way of running a threaded server and that is what 
ThreadedSOAPServer will do.
 Anyhow, do you have a short example or
documentation link handy on how to get ThreadedSOAPServer running?
SOAPpy documentation same as googling for it sadly weren't very
extensive on that... :/
Just change SOAPServer to ThreadedSOAPServer everywhere you use it.
I should say I haven't actually done this, I just looked at the source for 
SOAPpy/Server.py. It has
class SOAPServer(SOAPServerBase, SocketServer.TCPServer):
  ...
and
class ThreadingSOAPServer(SOAPServerBase, SocketServer.ThreadingTCPServer):
  ...
so the only difference between the two is that ThreadingSOAPServer is based on ThreadingTCPServer 
which has the behaviour you want. For more details see the docs and source for the SocketServer module.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with this script

2005-04-23 Thread Kent Johnson
John Carmona wrote:
I have decided to merge the 2 scripts. First I should have a menu asking 
me if I want to compute areas or volumes. Then depending on the choice 
it should display the relevant menu. My first menu comes on but if I 
select "b" or "c" the script does not run. The error message points out 
that "print_options()" or "print_options_2()" are not defined. Could 
somebody point me into the right direction, thanks.
The problem is that you are calling task_options() before print_options() and print_options_2() are 
defined.

A good practice is to put all your function definitions first in the file, then put the main code 
that calls them at the end. So you would have
def task_options():
  ...

def print_options():
  ...
def print_options_2():
  ...
Then start the main program by calling
task_options()
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterator question for a toy class

2005-04-23 Thread Rich Krauter
Kent Johnson wrote:
Rich Krauter wrote:
2) Or, if you really want your __eq__ method to use the iterator 
returned by __iter__(),

def __eq__(self, other):
for i, j in map(None,self, other):
if i != j:
return False
return True

That's not right either, it will compare Foo([None], []) == Foo([], []) 
for example.
Kent,
Yikes, I should have seen that. Thanks for pointing out the error.
Rich
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re Help with this script

2005-04-23 Thread John Carmona
Thanks Kent, it is working now. Is this what you meant in your reply? 
Because if I set up the main code at the end of the script I was still 
getting an error message.

Also, what do I need to use if for example I want my code to rerun once I 
have computed let's say a volume. Right now the execution of the script 
gives me "None" at the end.

Thanks
JC
--
#By J Carmona
#Programme that compute volumes or surfaces
##First menu is for the calculation of area
##Second menu is for the calculation of volume
##First ask the user what he wants to do
running = True
def area_rect():
   length = input("Length: ")
   width = input ("Width: ")
   print "The area is: ",length*width
def area_circ():
   radius = input("What is the radius?: ")
   print "The area is approximately: ", 3.14159*(radius**2)
def area_squ():
   side = input ("What is the length of one side?: ")
   print "The area is: ", side*side
def area_tgle():
   base = input ("What is the base of the triangle?: ")
   heigth = input ("What is the heigth of the triangle?: ")
   print "The area is: ",base*heigth/2
def vol_sph():
   radius = input("What is the radius?: ")
   print "The volume is: ", (4*3.14159*radius**3)/3
def vol_cube():
   side = input("Side: ")
   print "The volume is: ",side**3
def vol_box():
   width = input ("What is the width of the box?: ")
   length = input ("What is the length of the box?: ")
   depth = input ("What is the depth of the box?: ")
   print "The volume is: ", width*length*depth
def vol_cone():
   radius = input ("What is the radiux of the base of the cone?: ")
   heigth = input ("What is the heigth of the cone?: ")
   print "The volume is: ", (1/3)(3.144159*(radius**2))(heigth)
def task_options():
   print "---"
   print "Options:"
   print "a. Print options: "
   print "b. Do you want to calculate areas?: "
   print "c. Do you want to calculate volumes?: "
   print "d. Quit the programme"
   print "---"
   choice = raw_input("Choose an option: ")
   if choice == 'a':
   print task_options()
   elif choice == 'b':
   print print_options()
   elif choice == 'c':
   print print_options_2()
   elif choice == 'd':
   running = False
def print_options():
   print "--"
   print "Options:"
   print "a. print options"
   print "b. calculate circle area"
   print "c. calculate square area"
   print "d. calculate rectangle area"
   print "e. calculate triangle area"
   print "f. quit the programme"
   print "--"
   choice = raw_input("Choose an option: ")
   if choice == 'a':
   print_options()
   elif choice == 'b':
   area_circ()
   elif choice == 'c':
   area_squ()
   elif choice == 'd':
   area_rect()
   elif choice == 'e':
   area_tgle()
   elif choice == 'f':
   print_options()
def print_options_2():
   print "--"
   print "Options:"
   print "a. print options"
   print "b. calculate the volume of a sphere"
   print "c. calculate the volume of a cube"
   print "d. calculate the volume of a box"
   print "e. calculate the volume of a cone"
   print "f. quit the programme"
   print "--"
   choice = raw_input("Choose an option: ")
   if choice == 'a':
   print_options()
   elif choice == 'b':
   vol_sph()
   elif choice == 'c':
   vol_cube()
   elif choice == 'd':
   vol_box()
   elif choice == 'e':
   vol_cone()
   elif choice == 'e':
   print_options()
#Call starting menu
print task_options()

--
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re Help with this script

2005-04-23 Thread Max Noel
On Apr 23, 2005, at 15:44, John Carmona wrote:
Thanks Kent, it is working now. Is this what you meant in your reply? 
Because if I set up the main code at the end of the script I was still 
getting an error message.

Also, what do I need to use if for example I want my code to rerun 
once I have computed let's say a volume. Right now the execution of 
the script gives me "None" at the end.

Thanks
JC
	Here's an example of a script that will print "Yo." until you answer 
"n" or "no" (in any capitalization) to it. It should help you do what 
you want.

#!/usr/bin/env python
while True:
print "yo."
onceMore = raw_input("Once more?").strip().lower()
if "no".startswith(onceMore):
break
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re Help with this script

2005-04-23 Thread Kent Johnson
John Carmona wrote:
Thanks Kent, it is working now. Is this what you meant in your reply? 
Because if I set up the main code at the end of the script I was still 
getting an error message.
Yes, that's what I meant, though you just need
task_options()
rather than
print task_options()
When you say print task_options() you are asking the program to call task_options() and print the 
value returned. task_options() doesn't return a value, it does all the printing, etc. itself. So 
Python uses the default return value which is None. That's why the program prints "None" at the end.

Also, what do I need to use if for example I want my code to rerun once 
I have computed let's say a volume. Right now the execution of the 
script gives me "None" at the end.
You have to put a loop somewhere. Perhaps in task_options () you could have a loop that repeatedly 
asks for input and processes it. Since you are doing this as a learning exercise I won't show you 
how; give it a try and ask again if you have trouble.

You can find a little about while loops here:
http://docs.python.org/tut/node5.html
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python and Web Pages?

2005-04-23 Thread Paul Tader
I have a couple programs/scripts that I want to write that need to be 
web-based.  Can Python (and a little HTML) accomplish this?  Or are 
other languages like PHP, or Perl better suited?

A little more detail:
One project is to make a web page that users login to with a name and 
password, choose from a list of "canned" directory structure (ie. how 
many subdirectories, top-level name, maybe permissions, etc), hit a "GO" 
button and then the directories are made.

Another example is a web-based form that users interface with a mySQL 
database.  Simple additions/changes/deletions.  Basic stuff.

Thanks,
Paul

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python and Web Pages?

2005-04-23 Thread Kent Johnson
Paul Tader wrote:
I have a couple programs/scripts that I want to write that need to be 
web-based.  Can Python (and a little HTML) accomplish this?  Or are 
other languages like PHP, or Perl better suited?
Yes, Python can do this nicely. You can write CGI programs in Python or use one of the many web 
frameworks available. See
http://www.python.org/topics/web/
http://www.python.org/moin/WebProgramming
for some starting points; you probably want to write a CGI.

One project is to make a web page that users login to with a name and 
password, choose from a list of "canned" directory structure (ie. how 
many subdirectories, top-level name, maybe permissions, etc), hit a "GO" 
button and then the directories are made.
If you mean to make the directories on the user's machine, I don't think this is possible with just 
HTML and a browser. You could do it with a signed Java applet. If you mean to make the directories 
on the server then yes, you can do this.

Another example is a web-based form that users interface with a mySQL 
database.  Simple additions/changes/deletions.  Basic stuff.
Yes, you can do this in Python.
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python and Web Pages?

2005-04-23 Thread Jay Loden
I use both Python and PHP on my website to do a variety of tasks.  Some things 
PHP can do much easier than Python, but if you're doing simple things like 
form handling, Python will do nicely.  

If you're comfortable with Python, use it.  I find Python much easier to work 
with than PHP for a lot of things, but PHP works better with dynamic content 
within html, so I use each one where it's easiest. However, if you're not 
familiar with PHP, then I definitely wouldn't go out and learn PHP for this; 
just stick with Python because you'll get it done faster when you're 
comfortable.

-Jay

On Saturday 23 April 2005 05:09 pm, Paul Tader wrote:
> I have a couple programs/scripts that I want to write that need to be
> web-based.  Can Python (and a little HTML) accomplish this?  Or are
> other languages like PHP, or Perl better suited?
>
>
> A little more detail:
>
> One project is to make a web page that users login to with a name and
> password, choose from a list of "canned" directory structure (ie. how
> many subdirectories, top-level name, maybe permissions, etc), hit a "GO"
> button and then the directories are made.
>
> Another example is a web-based form that users interface with a mySQL
> database.  Simple additions/changes/deletions.  Basic stuff.
>
>
> Thanks,
> Paul
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] design questions: pythonic approach to ostriches

2005-04-23 Thread Brian van den Broek
Hi all,
I am wondering about the Pythonic way to handle the problem of 
ostriches, emus, and penguins. (I cannot recall from where I got the 
example.)

Here's what I mean:
class Bird(object):
def fly(self):
# flying logic here
def lay(self):
# egg-laying logic here
# more bird methods
class Ostrich(Bird):
# ostriches can't fly, so what to do?
I've explored a number of solutions; here they are with what I see as 
to cons and problems:

The simplest thing is to emulate the ostrich and pretend the problem 
doesn't exist. But, putting one's head in the sand looks likely to 
cause troubles in that this route break encapsulation, requiring 
callers to know enough not to call the fly method of an ostrich. So, 
that's no good.

class Ostrich(Bird):
def fly(self):
pass
seems only marginally better, in that it gives the external appearance 
of flight, whereas what is needed is a "Hey, I don't fly" signal.

The next thought was to over-ride Ostrich.fly as
def fly(self):
 raise NotImplementedError
That seems better, but also a bit confusing; the way I understand it, 
NotImplementedError is, in the first instance, for abstract classes or 
for marking work in progress. But Ostrich.fly doesn't fit either case.

That makes me think to define a custom exception, say
class OstrichError(NotImplementedError):
'''A custom exception for cases of the "Ostrich problem".
Intended to be raised by methods in a subclass over-riding methods
of the parent which don't make sense for the subclass to actually
implement.'''
def __init__(self):
NotImplementedError.__init__(self)
But, since the problem isn't one that my penetrating genius 
discovered, I am inclined to think that were this the ideal solution, 
there'd be a (better named) exception class builtin to Python already.

A complicated class hierarchy like
class Bird(object):
# bird logic
class FlyingBird(Bird):
def fly(self):
# flying logic here
class FlightlessBird(Bird):
# any particularly flightless logic here
class Ostrich(FlightlessBird):
# ostrich logic
seems an invitation to difficulty. My analogy will soon break, but 
some birds build nests and sing, others, no so much, etc. Flat is soon 
to give way to deeply nested.

I also tried to delete the inherited Bird.fly method within 
Ostrich.__init__, but

class Ostrich(Bird):
def __init__(self):
del self.__dict__['fly']
raises a KeyError, whereas
def __init__(self):
del Ostrich.__dict__['fly']
raises:
TypeError: object does not support item deletion
Do I have the syntax of the last approach wrong? Or is there no way to 
remove a method from a class? If the latter, what to do about 
flightless fowl?

Thanks and best,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterator question for a toy class

2005-04-23 Thread Marcus Goldfish
> - As Rich pointed out, making Foo into it's own iterator by adding a next()
> method is not a good idea. A simple way to define your own iterator is to
I see that an iterator is conceptually distinct from the container
object it iterates over, but I am confused that both the iterator and
container implement __iter__() to support the iterator protocol.  In
my original Foo implementation, __iter__() returned a list, which
supports the iterator protocol, so it "just worked" (albeit not for
all cases, and not efficiently).  In general, though, how would I
implement my own iterator (not using generator functions)?  Would I
have to have a FooIterator class?  What would FooIterator.__iter__()
return?

> make __iter__() into a generator function like
... so gfs look much easier!  This is the first concrete use for gf's
I've found in my code so far, and it rocks-- is it always possible to
implement an iterator using gfs?  Is there a performance issue to be
aware of when using gfs?

> you want. A simple definition for __eq__() that finds these unequal would be
>   def __eq__(self, other):
> return self.head == other.head and self.tail == other.tail
Ok, I like the modified __eq__(), but now I want my Foo class to store
the head and tail lists as private attributes (self.__head,
self.__tail).  Is it pythonic to modify the __eq__() method to:

   def __eq__(self, other):
  return self.__head == other._Foo__head and self.__tail == other._Foo__tail

or is this too restrictive (e.g., perhaps I wish to compare a Foo and
Bar class as correlated list sequences.  It is likely that
other._Foo__head will fail for a Bar).

> - If you define __eq__() you should also define __ne__(). Alteratively you can
... because it seems that Foo1 != Foo2 will fail otherwise.  Why is that?

Thanks (you too, Rich) for the very helpful comments!
Marcus
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design questions: pythonic approach to ostriches

2005-04-23 Thread Kent Johnson
Brian,
I think you have done a great job of demonstrating that design has to be evaluated in the light of 
requirements. There are probably scenarios where each of these solutions makes sense. Without 
knowing how it is to be used, there is no way to pick the 'right' one.

For example in a bird simulation it might be fine to have Ostrich.fly() do nothing. Possibly the 
version that throws an exception would be useful there also. The class hierarchy with FlyingBird is 
maybe more 'correct' but I don't know that it would be any easier to use in practice.

If you make Ostrich.fly() raise AttributeError it will look to the caller like it is not 
implemented...NotImplementedError seems appropriate as well. If you want to define your own 
exception it can be as simple as
class FlightlessBirdException(Exception):
  pass

Kent
Brian van den Broek wrote:
Hi all,
I am wondering about the Pythonic way to handle the problem of 
ostriches, emus, and penguins. (I cannot recall from where I got the 
example.)

Here's what I mean:
class Bird(object):
def fly(self):
# flying logic here
def lay(self):
# egg-laying logic here
# more bird methods
class Ostrich(Bird):
# ostriches can't fly, so what to do?
I've explored a number of solutions; here they are with what I see as to 
cons and problems:

The simplest thing is to emulate the ostrich and pretend the problem 
doesn't exist. But, putting one's head in the sand looks likely to cause 
troubles in that this route break encapsulation, requiring callers to 
know enough not to call the fly method of an ostrich. So, that's no good.

class Ostrich(Bird):
def fly(self):
pass
seems only marginally better, in that it gives the external appearance 
of flight, whereas what is needed is a "Hey, I don't fly" signal.

The next thought was to over-ride Ostrich.fly as
def fly(self):
 raise NotImplementedError
That seems better, but also a bit confusing; the way I understand it, 
NotImplementedError is, in the first instance, for abstract classes or 
for marking work in progress. But Ostrich.fly doesn't fit either case.

That makes me think to define a custom exception, say
class OstrichError(NotImplementedError):
'''A custom exception for cases of the "Ostrich problem".
Intended to be raised by methods in a subclass over-riding methods
of the parent which don't make sense for the subclass to actually
implement.'''
def __init__(self):
NotImplementedError.__init__(self)
But, since the problem isn't one that my penetrating genius discovered, 
I am inclined to think that were this the ideal solution, there'd be a 
(better named) exception class builtin to Python already.

A complicated class hierarchy like
class Bird(object):
# bird logic
class FlyingBird(Bird):
def fly(self):
# flying logic here
class FlightlessBird(Bird):
# any particularly flightless logic here
class Ostrich(FlightlessBird):
# ostrich logic
seems an invitation to difficulty. My analogy will soon break, but some 
birds build nests and sing, others, no so much, etc. Flat is soon to 
give way to deeply nested.

I also tried to delete the inherited Bird.fly method within 
Ostrich.__init__, but

class Ostrich(Bird):
def __init__(self):
del self.__dict__['fly']
raises a KeyError, whereas
def __init__(self):
del Ostrich.__dict__['fly']
raises:
TypeError: object does not support item deletion
Do I have the syntax of the last approach wrong? Or is there no way to 
remove a method from a class? If the latter, what to do about flightless 
fowl?

Thanks and best,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterator question for a toy class

2005-04-23 Thread Kent Johnson
Sending to the list, originally this went just to Marcus...
Marcus Goldfish wrote:
I'm trying to understand custom iterators in Python, and created the
following toy class for sequence comparison, which seems to work:
class Foo(object):
   """A toy class to experiment with __eq__ and __iter__"""
   def __init__(self, listA, listB):
  self.head, self.tail = listA, listB
   def __iter__(self):
  return iter(self.head[:]+self.tail[:])
   def __eq__(self, other):
  """Foo instances are equal if their respective subsequences,
  head, tail, are in the same order"""
  diff = [i for i, j in zip(self, other) if i != j]
  return len(diff) == 0
I'm not really sure if I'm implementing iter() correctly, for
instance: should I make copies of the sublists?  Should I try to
implement my own next() method?
A few comments:
- A semantic point - you haven't created a custom iterator, you have created a 
class that is
iterable. The actual iterator is the standard list iterator.
- You actually copy head and tail twice in __iter__ - once explicitly with [:] 
and once with + which
makes a new list. Neither copy is needed.
- As Rich pointed out, making Foo into it's own iterator by adding a next() 
method is not a good
idea. A simple way to define your own iterator is to make __iter__() into a 
generator function like
this:
  def __iter__(self):
for i in self.head:
  yield i
for i in self.tail:
  yield i
- __eq__() will say that Foo([1,2], [3,4]) == [1,2,3,4] which may not be what 
you want. If not then
put in a test for isinstance(other, Foo)
- __eq__() will say that Foo([1], [2]) == Foo([1, 2], []) which may not be what 
you want. A simple
definition for __eq__() that finds these unequal would be
  def __eq__(self, other):
return self.head == other.head and self.tail == other.tail
- If you define __eq__() you should also define __ne__(). Alteratively you can 
define __cmp__().
Reference on iterators:
http://docs.python.org/lib/typeiter.html
Reference on __eq__():
http://docs.python.org/ref/customization.html
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design questions: pythonic approach to ostriches

2005-04-23 Thread Rich Krauter
Brian van den Broek wrote:
Hi all,
I am wondering about the Pythonic way to handle the problem of 
ostriches, emus, and penguins. (I cannot recall from where I got the 
example.)

Here's what I mean:
class Bird(object):
def fly(self):
# flying logic here
def lay(self):
# egg-laying logic here
# more bird methods
class Ostrich(Bird):
# ostriches can't fly, so what to do?
I've explored a number of solutions; here they are with what I see as to 
cons and problems:

The simplest thing is to emulate the ostrich and pretend the problem 
doesn't exist. But, putting one's head in the sand looks likely to cause 
troubles in that this route break encapsulation, requiring callers to 
know enough not to call the fly method of an ostrich. So, that's no good.

class Ostrich(Bird):
def fly(self):
pass
seems only marginally better, in that it gives the external appearance 
of flight, whereas what is needed is a "Hey, I don't fly" signal.

The next thought was to over-ride Ostrich.fly as
def fly(self):
 raise NotImplementedError
That seems better, but also a bit confusing; the way I understand it, 
NotImplementedError is, in the first instance, for abstract classes or 
for marking work in progress. But Ostrich.fly doesn't fit either case.

That makes me think to define a custom exception, say
class OstrichError(NotImplementedError):
'''A custom exception for cases of the "Ostrich problem".
Intended to be raised by methods in a subclass over-riding methods
of the parent which don't make sense for the subclass to actually
implement.'''
def __init__(self):
NotImplementedError.__init__(self)
But, since the problem isn't one that my penetrating genius discovered, 
I am inclined to think that were this the ideal solution, there'd be a 
(better named) exception class builtin to Python already.

A complicated class hierarchy like
class Bird(object):
# bird logic
class FlyingBird(Bird):
def fly(self):
# flying logic here
class FlightlessBird(Bird):
# any particularly flightless logic here
class Ostrich(FlightlessBird):
# ostrich logic
seems an invitation to difficulty. My analogy will soon break, but some 
birds build nests and sing, others, no so much, etc. Flat is soon to 
give way to deeply nested.

I also tried to delete the inherited Bird.fly method within 
Ostrich.__init__, but

class Ostrich(Bird):
def __init__(self):
del self.__dict__['fly']
raises a KeyError, whereas
def __init__(self):
del Ostrich.__dict__['fly']
raises:
TypeError: object does not support item deletion
Do I have the syntax of the last approach wrong? Or is there no way to 
remove a method from a class? If the latter, what to do about flightless 
fowl?

Thanks and best,
Brian vdB

Brian,
I've seen the strategy pattern used in this kind of scenario. Your 
strategies can be encapulated classes, and methods within the Bird 
classes delegate to the strategy classes - so you achieve desired 
behavior though composition, rather than inheritance.

Here's a quick example (which doesn't really address any of your 
questions and probably has its own problems):

class CantFly(object):
def fly(self):
print "I can't fly"
class CanFly(object):
def fly(self):
print "I can fly"
class Bird(object):
def __init__(self,flightBehavior):
self.flightBehavior = flightBehavior
def fly(self):
self.flightBehavior.fly()
b1 = Bird(CantFly())
b2 = Bird(CanFly())
for b in (b1,b2):
b.fly()
Good luck.
Rich
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterator question for a toy class

2005-04-23 Thread Kent Johnson
Marcus Goldfish wrote:
I see that an iterator is conceptually distinct from the container
object it iterates over, but I am confused that both the iterator and
container implement __iter__() to support the iterator protocol.
I think this is to simplify the Python runtime. 'for i in c' will work if c is an iterable container 
or an actual iterator. In either case the runtime can just call c.__iter__() and get an iterator.

  In
my original Foo implementation, __iter__() returned a list, which
supports the iterator protocol, so it "just worked" (albeit not for
all cases, and not efficiently).  
Actually your Foo.__iter__() returned an iterator over a list. You called iter() on a list, which 
returns an iterator.

In general, though, how would I
implement my own iterator (not using generator functions)?  Would I
have to have a FooIterator class?  
Yes, that would be the simplest way.
What would FooIterator.__iter__()
return?
self.
Here's an attempt at Foo.__iter__() that creates a custom iterator object...no, actually, it is so 
awkward I'm not going to bother. FooIterator has to keep a lot of state - the current list being 
indexed and the current index. Use a generator function!

make __iter__() into a generator function like
... so gfs look much easier!  This is the first concrete use for gf's
I've found in my code so far, and it rocks-- is it always possible to
implement an iterator using gfs?  
Yes, at least there are no restriction I know of. Maybe some strange case where it doesn't make 
sense. The docs say, "Python's generators provide a convenient way to implement the iterator 
protocol. If a container object's __iter__() method is implemented as a generator, it will 
automatically return an iterator object (technically, a generator object) supplying the __iter__() 
and next() methods."

Is there a performance issue to be
aware of when using gfs?
Not that I know of. Try it and see. It wouldn't surprise me to find that gfs are faster; generally 
the more you use builtin stuff the faster your code will run.

you want. A simple definition for __eq__() that finds these unequal would be
 def __eq__(self, other):
   return self.head == other.head and self.tail == other.tail
Ok, I like the modified __eq__(), but now I want my Foo class to store
the head and tail lists as private attributes (self.__head,
self.__tail).  Is it pythonic to modify the __eq__() method to:
   def __eq__(self, other):
  return self.__head == other._Foo__head and self.__tail == other._Foo__tail
You just need other.__head
or is this too restrictive (e.g., perhaps I wish to compare a Foo and
Bar class as correlated list sequences.  It is likely that
other._Foo__head will fail for a Bar).
It depends on how you want to use Foo. Since it is a toy you can make it do 
whatever you want.
- If you define __eq__() you should also define __ne__(). Alteratively you can
... because it seems that Foo1 != Foo2 will fail otherwise.  Why is that?
Because Python doesn't assume that __eq__() and __ne__() are inverses. See
http://docs.python.org/ref/customization.html
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CLS? (Joseph Quigley)

2005-04-23 Thread Alan Gauld
> Drat. I do like the \n * 100 though but that really wasn't what I
was
> getting at. Do you know what the command is for Mac

The problem is that it depends not just on the OS.

MacOS X is Unix and that can support zillions of different terminal
types each with their own control codes. These are mapped to a
standard set in a database called (depending on your Unix version!)
terminfo or termcap (cap=capability) and manipulated by a utility
called tty. The difficulty is that not all terminals support all
capabilities so you have to call stty to first find out if the
capability exists, then use stty again to set it. - Altogether
far too messy for most mortals.

The more common route on Unix is to use the curses library which
provides a windowing toolkit for a dumb terminal. The default
window is the whole screeen and curses allows you to position the
cursor at any point on screen, clear the screen(Or any rectangular
section of it) and so on.

Try man terminfo for the full story, and man curses if you want
to go down that route. Programs like vi and top are written using
curses.

> considering not clearing the screen. What a hassle.

As someone else said thats actually the right approach on a Unix box.
Consider that some folks might be using an old paper teletype where
the text just prints onto paper which scrolls off the top. What
happens
with my print '\n'*100 there? - they get a lot of white paper!

Now on DOS MIcrosoft used a thing called the ANSI terminal which is
a kind of virtual terminal standard that a lot of terminal
manufacturers
could support in addition to their own standards. It was pretty dumb
but by adopting a standard QBASIC et al could implement screen
controlls
in assembler so they were both fast and reliable. But it only workled
because the PC only supported that one standard.

The joys of multi platform computing! :-)

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with this script

2005-04-23 Thread Alan Gauld
> should display the relevant menu. My first menu comes on but if I
select "b"
> or "c" the script does not run. The error message points out that
> "print_options()" or "print_options_2()" are not defined. Could
somebody
> point me into the right direction, thanks.

Thats because you define them after you call task_options().
So when task_options runs you haven't defined the functions
it is trying to call.

Put the code that actually calls your functions at the very end of the
script.


>
> 
-
> #By J Carmona
> #Programme that compute volumes or surfaces
> ##First menu is for the calculation of area
> ##Second menu is for the calculation of volume
>
> ##First ask the user what he wants to do
> running = True
>
> def area_rect():
> length = input("Length: ")
> width = input ("Width: ")
> print "The area is: ",length*width
>
> def area_circ():
> radius = input("What is the radius?: ")
> print "The area is approximately: ", 3.14159*(radius**2)
>
> def area_squ():
> side = input ("What is the length of one side?: ")
> print "The area is: ", side*side
>
> def area_tgle():
> base = input ("What is the base of the triangle?: ")
> heigth = input ("What is the heigth of the triangle?: ")
> print "The area is: ",base*heigth/2
>
> def vol_sph():
> radius = input("What is the radius?: ")
> print "The volume is: ", (4*3.14159*radius**3)/3
>
> def vol_cube():
> side = input("Side: ")
> print "The volume is: ",side**3
>
> def vol_box():
> width = input ("What is the width of the box?: ")
> length = input ("What is the length of the box?: ")
> depth = input ("What is the depth of the box?: ")
> print "The volume is: ", width*length*depth
>
> def vol_cone():
> radius = input ("What is the radiux of the base of the
cone?: ")
> heigth = input ("What is the heigth of the cone?: ")
> print "The volume is: ", (1/3)(3.144159*(radius**2))(heigth)
>
>
> def task_options():
> print "---"
> print "Options:"
> print "a. Print options: "
> print "b. Do you want to calculate areas?: "
> print "c. Do you want to calculate volumes?: "
> print "d. Quit the programme"
> print "---"
> choice = raw_input("Choose an option: ")
> if choice == 'a':
> print task_options()
> elif choice == 'b':
> print print_options()
> elif choice == 'c':
> print print_options_2()
> elif choice == 'd':
> running = False
> print task_options()
>
>
> def print_options():
> print "--"
> print "Options:"
> print "a. print options"
> print "b. calculate circle area"
> print "c. calculate square area"
> print "d. calculate rectangle area"
> print "e. calculate triangle area"
> print "f. quit the programme"
> print "--"
> choice = raw_input("Choose an option: ")
> if choice == 'a':
> print_options()
> elif choice == 'b':
> area_circ()
> elif choice == 'c':
> area_squ()
> elif choice == 'd':
> area_rect()
> elif choice == 'e':
> area_tgle()
> elif choice == 'f':
> print_options()
> #Call starting menu
> print_options()
>
> def print_options_2():
> print "--"
> print "Options:"
> print "a. print options"
> print "b. calculate the volume of a sphere"
> print "c. calculate the volume of a cube"
> print "d. calculate the volume of a box"
> print "e. calculate the volume of a cone"
> print "f. quit the programme"
> print "--"
> choice = raw_input("Choose an option: ")
> if choice == 'a':
> print_options()
> elif choice == 'b':
> vol_sph()
> elif choice == 'c':
> vol_cube()
> elif choice == 'd':
> vol_box()
> elif choice == 'e':
> vol_cone()
> elif choice == 'e':
> print_options()
> #Call starting menu
> print_options()
> 
---
>
> JC
>
>
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design questions: pythonic approach to ostriches

2005-04-23 Thread Alan Gauld
> I am wondering about the Pythonic way to handle the problem of
> ostriches, emus, and penguins. (I cannot recall from where I got the
> example.)

Its not really a Python issue its one of several similar conundrums in
OOP in any language.

My solution for this one:

class Bird()...

class FlightlessBird(BIrd):...

class FlyingBird(Bird):...

class Ostritch(FlightlessBird):...

class Emu(FlighlessBird):...

class Seagull(FlyingBird):...

etc.

But it gets complicated when you get more exceptions and you wind up
with
an explosion of classes. So in general there is a design pattermn that
helps out called a decorator(I hope thats the right one...).

The other approach(which I prefer) is to use a concept called a Mixin
(as mixing in flavours in an ice cream parlour - it was introduced in
the Lisp OO Language Flavors...). Mixins are little classes that
define
behaviour in a generic way. You then use multiple inheritance to
create the mix you need:

class Bird

class Flight: # used for birds or planes or rockets...

class Nesting:

class TreeDweller

class HouseDweller...

class Swallow(Bird, Flight, HouseDweller, Nesting)

class  Ostritch(Bird)

class Owl(Bird,Flight, Nesting, TreeDweller)...

and so on.

But this only works well in languages that support dynamic
binding, and multiple inheritance - like Python!

But as I said similar problems exist and there is no simple answer.
You pick the one with least pain for your situation. (A common
example is where do Square and Rectangle sit in a heirarchy of
shapes?)

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design questions: pythonic approach to ostriches

2005-04-23 Thread Brian van den Broek
Alan Gauld said unto the world upon 2005-04-23 15:18:
I am wondering about the Pythonic way to handle the problem of
ostriches, emus, and penguins. (I cannot recall from where I got the
example.)

Its not really a Python issue its one of several similar conundrums in
OOP in any language.

Thanks Alan, Kent, and Rich for the replies.
Since posting I retraced my steps and found where I came across the 
example: an OK book Object-Oriented Thought Process, The, Second 
Edition By Matt Weisfeld that I read on safari 
. Weisfled points 
out the ostrich problem has often been cited by those who say "don't 
inherit, compose".

Alan's second solution (the mixin approach), seems to go in that 
direction. (I'm not attributing endorsement of "don't inherit" to any 
of the respondents!) In spirit, if not details, Rich's Strategy 
Pattern suggestion seems to point in that direction, too.

Any of these solutions (or the alternatives in my original post) seem 
likely to be messy in some contexts. I take Kent and Alan's points  to 
that effect.

I do remain a bit surprised that there seems to be no way to implement 
what I naively thought would be the obvious solution -- to remove an 
inherited method from the instance's dictionary.

Anyway, thanks again to all,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Does Python have anything like Perls format output?

2005-04-23 Thread Tom Tucker
Good evening!  Does Python have a print function similar to Perl
format output (example below)?

Thanks

Tom

format STDOUT =
@< @ @<<< [EMAIL PROTECTED] [EMAIL PROTECTED]
$code, $date,$descript,$amt,   $balance
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Does Python have anything like Perls format output?

2005-04-23 Thread Danny Yoo


On Sat, 23 Apr 2005, Tom Tucker wrote:

> Good evening!  Does Python have a print function similar to Perl
> format output (example below)?

Hi Tom,

Not exactly, but we can get something close, by using the String
Formatting operators.

http://www.python.org/doc/current/lib/typesseq-strings.html

The example above might be written as:

##
code = "hi"
date = "0420"
descript = "a test of formatting"
amt = 3.14
balance = 2.71
text = """
%-5s %4s %-19s %5.2f %5.2f
""" % (code, date, descript, amt, balance)
print text
##

If you have more questions, please feel free to bring them to the group.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design questions: pythonic approach to ostriches

2005-04-23 Thread Danny Yoo


> I do remain a bit surprised that there seems to be no way to implement
> what I naively thought would be the obvious solution -- to remove an
> inherited method from the instance's dictionary.


Hi Brian,

If we're trying to do this, we probably don't want to "inherit" from a
parent.  A subclass child is supposed to have, at the very least, the same
public methods as its parent.  For example, if we have a:

##
class Account:
def __init__(self, amount):
self.amount = amount

def withdraw(self, x):
assert x > 0
self.amount = self.amount - x

def report(self):
print "You have ", self.amount, "dollars"
###


And we'd like to reuse this, but for something that doesn't report itself,
we shouldn't use inheritance:

###
class SecretAccount(Account):
def report(self):
pass
###


This SecretAccount is now pretending to be an account that doesn't have a
usable report() method.

###
>>> Account(5).report()
You have  5 dollars
>>> SecretAccount(5).report()
>>>
###



But we can get into trouble again, if, later on, Account is expanded to
have a few more additional functions:

##
class Account:  ## version 2
# [same as before]
def htmlReport(self):
print ("You have %d dollarshttp://mail.python.org/mailman/listinfo/tutor


[Tutor] Bandwidth Tester

2005-04-23 Thread Ali Polatel
   Hi Tutors,
   How can i write a simple bandwidth tester with Python?
   Regards,
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design questions: pythonic approach to ostriches

2005-04-23 Thread Brian van den Broek
Danny Yoo said unto the world upon 2005-04-23 22:16:

I do remain a bit surprised that there seems to be no way to implement
what I naively thought would be the obvious solution -- to remove an
inherited method from the instance's dictionary.

Hi Brian,
If we're trying to do this, we probably don't want to "inherit" from a
parent.  A subclass child is supposed to have, at the very least, the same
public methods as its parent.  For example, if we have a:




But we can get into trouble again, if, later on, Account is expanded to
have a few more additional functions:
##
class Account:  ## version 2
# [same as before]
def htmlReport(self):
print ("You have %d dollars
And now, suddenly, SecretAccount again has a method that shows information
that it probably doesn't want out in the open.
The issue that that SecretAccount is really not trying to be an "Account":
it's just trying to reuse its functionality.  Instead of doing things with
inheritance, we're probably looking for delegation:
###
class SecretAccount:
def __init__(self, amount):
self.account = Account(amount)
def withdraw(self, x):
self.account.withdraw(x)
###
And now we're more isolated from changes to the Account class.
There are some more Pythonic idioms to make delegation easier to code.
And the example above is hideously toyish.  *grin*
But I hope the idea's a little clearer: inheritance ties the subclass down
to at least what the superclass has promised, and in many cases, that's
not what we want.

Thanks Danny, that's really helpful.
I still think the "delete an inherited method" approach could be 
useful in some cases, but your example certainly shows it would come 
with its own sack of troubles, too. Given that it would take a 
language change, and wouldn't be less troubled than any of the other 
available approaches, I can now happily agree that it wouldn't be 
worth it.

Best to all,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor