A java hobbyist programmer learning python
Chris Rebert
clp2 at rebertia.com
Sat Jan 17 20:27:56 EST 2009
On Sat, Jan 17, 2009 at 5:11 PM, elhombre <elhmbre at ozemail.com.au> wrote:
> Hello, below is my first fragment of working python code. As you can see it
> is very java like as that is all I know. Is this the right approach to be
> taking?
> Should I be taking a different approach? Thanks in advance.
>
> import sys
>
> class Calculator():
>
> def __init__(self):
> self.operator = sys.argv[1]
> self.arg1 = sys.argv[2]
> self.arg2 = sys.argv[3]
>
> def getOperator(self):
> return sys.argv[1]
>
> def getArg1(self):
> return sys.argv[2]
>
> def getArg2(self):
> return sys.argv[3]
Delete the 3 Java-ish accessor methods; good Python style just uses
the attributes directly (i.e. self.operator instead of
self.getOperator()).
>
> def calculate(self):
> if self.getOperator() == '+' :
> return int(self.getArg1()) + int(self.getArg2())
> elif self.getOperator() == '*' :
> return int(self.getArg1()) * int(self.getArg2())
> elif self.getOperator() == '/' :
> return int(self.getArg1()) / int(self.getArg2())
> elif self.getOperator() == '-' :
> return int(self.getArg1()) - int(self.getArg2())
> else:
> return 'Wrong argument supplied'
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
def sub(x, y):
return x - y
OPER2FUNC = {'+' : add, '-' : sub}
print OPER2FUNC['+'](3,4) #==> 7
You can use the same technique with the functions in the `operator`
module to significantly shorten your calculate() method.
Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
More information about the Python-list
mailing list