Class variables vs instance variables could seem a bit strange, if you have no OOP experience, but after a few thausand lines of code they become logical. So, in around two days of programming you will be getting it intuitively 🙂
Ok, let’s take a look at our FootballPlayer class, looking like this:
1 2 3 4 5 6 |
class FootballPlayer: min_salary = 650 def __init__(self, name, number): self.name = name self.number = number |
As the minimal salary in Bulgaria is currently 650 BGN, that is the minimal salary of every football player, upon creation. So, any player created will be created with this minimal salary. In the example below, I am creating two football player instances – vitosh and joe. Without assigning them any min_salary , they get the one from the class, automatically assigned to them:
1 2 3 4 5 6 |
>>> from main import FootballPlayer >>> vitosh = FootballPlayer("Vitosh", 9) >>> vitosh.min_salary 650 >>> FootballPlayer.min_salary 650 |
If we change the class variable min_salary, then the property is changed for every instance, including the already created ones:
1 2 3 4 5 6 |
>>> FootballPlayer.min_salary = 7000 >>> joe = FootballPlayer("Joe", 9) >>> joe.min_salary 7000 >>> vitosh.min_salary 7000 |
And it makes sense. What also makes sense (but only for some people), is that we may use the __class__ dunder of a given instance, to change the class variable:
1 2 3 4 5 |
>>> vitosh.__class__.min_salary = 42 >>> vitosh.min_salary 42 >>> joe.min_salary 42 |
Enjoy!