A java hobbyist programmer learning python

2009-01-17 Thread elhombre
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]

   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'

x = Calculator()
y = x.calculate()
print y 


--
http://mail.python.org/mailman/listinfo/python-list


Re: A java hobbyist programmer learning python

2009-01-17 Thread elhombre
"Chris Rebert"  wrote in message 
news:mailman.7468.1232242083.3487.python-l...@python.org...

On Sat, Jan 17, 2009 at 5:11 PM, elhombre  wrote:

...


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


Thanks very much Chris. That is much more concise ! I have a lot of reading 
to do and a different mindset to work towards. 


--
http://mail.python.org/mailman/listinfo/python-list


Re: A java hobbyist programmer learning python

2009-01-17 Thread elhombre


"Paul Rubin"  wrote in message 
news:7xy6x9nzwd@ruckus.brouhaha.com...

Chris Rebert  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


Re: A java hobbyist programmer learning python

2009-01-17 Thread elhombre
"John Machin"  wrote in message 
news:5d2c588a-9b01-4a85-85b2-b132754e6...@o40g2000prn.googlegroups.com...

On Jan 18, 12:11 pm, "elhombre"  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]


Try this:

def __init__(self, operator, arg1, arg2):
   self.operator = operator
   self.arg1 = arg1
   self.arg2 = arg2

Then you can do
x1 = Calculator('+', '1.0', '2.0')
x2 = Calculator('-', '666', '42')
or
x3 = Calculator(*sys.argv[1:4])
if you're really desperate to use the command line args.



def getOperator(self):
return sys.argv[1]


Chris has already told you to give such accessor functions the flick,
but it should have done
   return self.operator


Thanks John.



--
http://mail.python.org/mailman/listinfo/python-list


Re: A java hobbyist programmer learning python

2009-01-17 Thread elhombre



"Steven D'Aprano"  wrote in message 
news:0182896d$0$8693$c3e8...@news.astraweb.com...

On Sun, 18 Jan 2009 11:11:45 +1000, elhombre 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?


You might find it very useful to read:

http://dirtsimple.org/2004/12/python-is-not-java.html

http://dirtsimple.org/2004/12/java-is-not-python-either.html




Should I be taking a different approach? Thanks in advance.


This is obviously a very minimal program, so I won't criticise you for
failing to do any error checking :-) However, I will make some broad
points:

* No getters and setters. Python takes a very permissive approach to
class attributes, taking the philosophy "we're all adults here". It's
easy to change a public attribute to a private attribute with a getter/
setter if you need to, so there's nothing to be gained by writing getters
for straight attribute access. It just makes things slow.

* Don't return error values, raise an exception. Setting up a
try...except block is really fast in Python, almost as fast as a pass
statement (according to my tests). Catching the exception itself is slow,
but most of the time you won't care about that.



Let me re-write your code in a more Pythonic way. This is not the only
way to do this, and it probably isn't the best way, but it may give you a
flavour for the way Python is usually written.


import sys
import operator

class Calculator():
   dispatch = {  # dispatch table mapping symbol to function
   '+': operator.add,
   '-': operator.sub,
   '*': operator.mul,
   '/': operator.truediv,
   }
   def __init__(self):
   self.operator = sys.argv[1]
   self.arg1 = int(sys.argv[2])
   self.arg2 = int(sys.argv[3])
   def calculate(self):
   func = self.dispatch[self.operator]
   return func(self.arg1, self.arg2)


if __name__ == '__main__':
   # run this block only when running as a script, not
   # when the module is being imported (say, for testing).
   x = Calculator('+', 23, 42)
   try:
   y = x.calculate()
   except KeyError:
   print "Unrecognised operator '%s'" % x.operator
   else:
   print y




--
Steven


Excellent links. Thanks Steven ! 


--
http://mail.python.org/mailman/listinfo/python-list