Python First Impressions
My language to learn this year is
Python. It seems like a good fit since I can still stay in the comfortable confines of .NET (in
IronPython) while learning a hip and trendy dynamic language.
After a few hours of reading through the standard introductory material, I thought I'd record my first impressions. It will be interesting to see if I still feel the same after some more time with Python.
Here is a pretty cut-and-dry "Hello World" program written in both C# and Python. Python purports to focus on readability and writability, so let's see how it stack up against my old pal C#
In C#
1: public class Program
2: {
3: private string world;
4:
5: public Program(string world)
6: {
7: this.world = world;
8: }
9:
10: public void Run()
11: {
12: Console.WriteLine("Hello " + world + "!");
13: }
14: }
15:
16: Program program = new Program("Earth");
17: program.Run();
In Python
1: class Program(object) :
2: def __init__(self, world) :
3: self.world = world
4:
5: def run(self) :
6: print "Hello " + self.world + "!"
7:
8: program = Program("Earth")
9: program.Run()
The first thing we notice is that the C# program is 17 lines and the Python program is 9 lines. That's a good start.
The second thing that jumps out is that Python does not use curly braces. Another bonus. Those things are all over the place in C#. I'm constantly having to borrow them from coworkers when I run out. Instead, Python starts a block with a colon and relies on indentation to figure out the end of the block. Nice, but I think I like Ruby’s straight-forward “begin / end” even better.
Of course, Python is a dynamic language so no worries about declaring things up-front. That's a big plus. Notice the “world” attribute isn’t declared in Python. It gets made up on the fly the first time it is assigned to in the constructor. Also, my program can be instantiated without making me type "new" like C# does. So far, so good ... all the same goodies without extra typing.
The constructor is identified by having the name “__init__”. Makes as much sense as any other constructor convention, I suppose. Maybe VB’s “New” is the clearest.
The only thing I’m not too sure about is this "self" business when declaring instance methods on my class. In C#, this is the "this" parameter for an instance method, but C# just assumes it, while Python makes me type it. Not sure about that one -- seems like a whole lot of extra hassle. Maybe this makes more sense down the road, but for now, it's really annoying.
On the whole thought, Python is definitely more readable and writable than C# and should be a hoot to use.