[Tutor] Function problem
Eri Mendz
jerimed at myrealbox.com
Sat Nov 6 10:44:36 CET 2004
On Fri, 5 Nov 2004, Bob Gailer wrote:
Hi Bob,
Thanks for the advanced version of the program. I'm not into classes yet
so pardon me if much of it is vague to me. Good study material
nevertheless, thanks.
--
Regards,
Eri Mendz
Using PC-Pine 4.61
>>
[snip own post]
> Since I enjoy OOP I thought I'd see what your program might look like using
> classes. Here's a cut at it:
>
> import sys
> class Menu:
> input_prompt = ''
> def prompt(self):
> print '[%s] - %s' % (self.__class__.__name__, self.menu_prompt)
> def act(self):
> if self.input_prompt:
> try:
> inp = raw_input(self.input_prompt)
> self.act_on_input(inp)
> except KeyboardInterrupt:
> pass
>
> class Numeric(Menu):
> def act_on_input(self, inp):
> try:
> inp = int(inp)
> print self.output_prompt % self.convert(inp)
> except ValueError:
> print 'Input must be numeric.'
>
> class Character(Menu):
> pass
>
> class C(Numeric):
> menu_prompt = 'convert to Celsius'
> input_prompt = 'enter fahrenheit temperature: '
> output_prompt = 'temp in C is %s'
> def convert(self, ctemp):
> return (9/5.0)*ctemp + 32
>
> class F(Numeric):
> menu_prompt = 'convert to Fahrenheit'
> input_prompt = 'enter centigrade temperature: '
> output_prompt = 'temp in F is %s'
> def convert(self, ftemp):
> return (ftemp - 32) * 5/9.0
>
> class P(Character):
> menu_prompt = 'print options'
> def act_on_input(self, inp):
> print_options()
>
> class Q(Character):
> menu_prompt = 'quit'
> input_prompt = 'Really quit program? [Y|N]: '
> def act_on_input(self, inp):
> if 'YES'.startswith(inp.upper()):
> sys.exit("bye")
> else:
> print_options()
>
> menu = [C(), F(), P(), Q()]
>
> def print_options():
> print '''
> THIS IS A TEMPERATURE CONVERSION PROGRAM.
> Options: '''
> for item in menu:
> item.prompt()
>
> print_options()
> while 1:
> choice = raw_input("select option: ").upper()
> for item in menu:
> if item.__class__.__name__ == choice:
> item.act()
> break
> else:
> print "invalid option"
> print "bye"
>
> What I like about this is that all the information for a choice is packaged
> in the class definition, and there is minimal redundant code.
>
> Bob Gailer
> bgailer at alum.rpi.edu
> 303 442 2625 home
> 720 938 2625 cell
>
>
>
More information about the Tutor
mailing list