Why We Shouldn’t Use Mutable Objects as Shared Data In Class
I know many of you are already familiar with it. This post is dedicated to those who are actually like me wasted time by learning only modules and how to use them. I have been using python for at least 3 years but there were so many lackings that I couldn’t imagine. Then I started my journey to the core concept, and with the language reference. I started loving and enjoying python so much that I started writing about it. Sorry for the blabbering.
Suppose, I have a class named Player, that has some attributes like name, age, and a shared list containing skills and a shared variable profession.
Now, let's create to instance object of class Player. I have declared p1, p2. Both of them will have the same profession as Footballer. Let’s change p2’s profession and let’s check if the p1’s profession also got changed or not.
Now, let’s set their skills. We all know that Messi is a great dribbler and good with freekicks, where Ronaldo on the other hand good with Penalty and Heading as he is always waiting for the ball in the D-box. Let’s call our function add_skill for both and let’s see what happens next.
Viola! What did we get? Both Messi and Ronaldo have the same skills. No matter what, p1 or p2 for which one I call add_skill functions; the skills got updated for both. Let’s correct our design for the class Player by making our list as an instance variable instead.
Now, we will see the difference below.
This might be so simple for the pro ninjas, but it could be helpful for the beginners like me. That’s why don’t use mutable objects as a shared variable. you can read and find out more on python’s documentation.