July 8, 2007
Python Classes and Variable Gotchas
I have been learning the hard way that Python has chosen a different route that most of the other OO languages that I have come to know and use. I may not have this 100% accurate yet, so please correct me if I err with this post, but what I have seen thus far (mostly in the form of hard to track down bugs where things aren't working as I intended them to) leads me to believe there are some either well planned but poorly communicated features or after thoughts in the language's implementation of common OO programming constructs.
The first and foremost of these undesirables are the use of implicit static variables. Instead of explicitly marking a variable on a class as static, or shared between instances, the implementers of Python buck the tradition and history of OO language implementations to make a variable defined on a class default to static. In fact the only way to make the static variable an instance variable is to declare and assign to it on the instance either in a method on the class using "self.VARIABLE" or outside of the class on the instance variable itself.
Of course one is able to "convert" the class level static variable to an instance by assigning to that variable on the on the instance. Of course, any mutable object like a List or Dictionary, you need to remember to ASSIGN to the variable not CHANGE it through something like self.MyDictionary['newkey'] = 'value' as this will remain a static shared variable.
Now, I will remain open minded and chalk up most of this frustration to still needing to get into a different mental model after years of C#, however, at some point this has got to make more sense to me that it currently does.
It certainly seems harder to express my intent than it does with C# at the present.