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.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to