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.

class Dog:
    tricks = []
    def __init__(self, name):
        self.name = name
    def add_trick(self, trick):
        self.tricks.append(trick)
    if __name__ == '__main__':
        d = Dog('Fido')
        e = Dog('Buddy')
        d.add_trick('roll over')
        e.add_trick('play dead')
        print(d.tricks)
        print(e.tricks)

On execution, the output is the following:

['roll over', 'play dead']
['roll over', 'play dead']

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:

class Dog:
    def __init__(self):
        self.tricks = []

Why did I even consider writing tricks = [] in the first place, you might ask. I think that idea arouse from the corresponding C++ notation:

class Dog {
public:
	void addTrick(const std::string& trick) {
		tricks.push_back(trick);
	}
private:
	std::vector<std::string> tricks;
};

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.