In this series of articles I will present some random things I've noticed when I started studying the Python programming language a while ago. I'm actually not very experienced in the language yet, as I don't get in touch with it that often. But I think if you also do your programming mainly in C++ and tend to use Python now and then, this might be for you.
This article is about class members. When I wrote my first Python class, I started off just as usual -- by creating a class and putting in some methods and member variables.
Everything went fine up to the moment I realized that all instances of that class happened to share the same internal state. After some research on the web, I've found a perfect example from the Python docs, so let's just take a look at it.
On execution, the output is the following:
As we can see, both class instances apparently share a single instance of the tricks list and operate on it.
The docs also state the solution to the problem, of course. Instead of declaring the tricks list inside the class, we simply assign the desired initial value to self.tricks at the first usage:
Why did I even consider writing tricks = [] in the first place, you might ask. I think that idea arouse from the corresponding C++ notation:
Here, the class attribute always needs to be declared explicitly.
Conclusion
In Python, there is no need to declare instance members explicitly. We simply write self.foo at first usage.
I the subsequent episodes of the series, I will probably write about the interactive Python interpreter, the style guide and some other interesting topics. Feel free to contact me on twitter: @ronalterde.