"Paul Rubin" <http://phr...@nospam.invalid> wrote in message
news:7xy6x9nzwd....@ruckus.brouhaha.com...
Chris Rebert <c...@rebertia.com> writes:
> class Calculator(): ...
Delete the 3 Java-ish accessor methods; good Python style just uses
the attributes directly (i.e. self.operator instead of
self.getOperator()).
I think I would get rid of the whole Calculator class unless there was
a good reason to keep it (i.e. you are going to have several
Calculators active in the program simultaneously). Just write
straightforward imperative code without bothering with the OO stuff
that is mandatory in Java.
Rather than have a long if-elif-else chain like this, you can use a
dictionary with functions as values. For example:
def add(x, y):
return x + y
These functions are already defined in the operator module, and you
can also define them inline with the lambda operator.
Here is my version of the program:
import sys
from operator import add, mul, sub, div
op, x, y = sys.argv[1:4]
opdict = {'+': add, '*': mul, '-': sub, '/': div}
try:
func = opdict[op]
except KeyError:
print 'wrong argument supplied'
sys.exit()
print func(int(x), int(y))
Note that like the original, it doesn't check for valid numeric args.
Good point about the class. I really only did that to begin to learn the
class syntax. I had not added any exception handling as I was taking it a
step at a time. Most of the first few hours were spent mucking around with
TextMate, Netbeans and Wing IDE. I finally got Netbeans working to the point
where something would run.
Thanks very much Paul.
--
http://mail.python.org/mailman/listinfo/python-list