A java hobbyist programmer learning python

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Jan 18 03:24:51 CET 2009


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



More information about the Python-list mailing list