How I Learned Python in an Hour
A while back I wrote about a code kata that I wrote, Roman Numerals in PHP. I decided that I would try to re-implement the same algorithm in different programming languages - both some I knew, and some i did not. My first choice was python.
I have written a bit of python earlier, but have never used it for anything important. I pretty much started from scratch.
Python is very sensitive to indentation
One of my biggest frustrations - until I found a tip that I needed to set soft-tabs as default for my python source files in Textmate. Go to Bundles->Bundle Editor->Show Bundle Editor. Find Python, and then Miscellaneous. Enter the following:
All python files should now use softwrap, instead of tabs. That worked for me.
All class methods must have a self parameter
At first I thought the python interpreter was taunting me. When calling a method it constantly told me that I send exactly one more parameter to the method than were expected. In other languages the reference to the current object are sent transparently. In Python it is also sent transparently, but you need to define it in the method signature in your class.
Files and classes does not match
My first instinct was to include my python class as a file and then instantiate it with
however this is wrong. The python file in which the class is placed is called a module in python, which is what I imported. This imported module can then contain functions and/or classes. From php I am used to - since I use auto loading extensively - that classnames and filenames match. This is not necessarily the case here. The correct way to instantiate the class is thus (the first three lines for a cli program to test the RomanNumerals class):
Class variables are not accessed with this or self
One thing I struggled with for a long time, was how to access my "constants". Since python does not support class constants, I used variables instead. And they were rather hard to reference. The correct way seems to be self.__class__.VARNAME
Take a look at the source for the python implementation of Roman Numerals on github.
