educative.io

Query on topic classes and Instance variables

here https://www.educative.io/courses/learn-object-oriented-programming-in-python/N7Gogn3nyx8#using-class-variables-smartly

In this example you said Wrong use of class variable, because it can be accessed by any instance

class Player:
  teamName = 'Liverpool'      # class variables
  formerTeams = []          # wrong use of class variables

  def __init__(self, name):
    self.name = name        # creating instance variables

p1 = Player('Mark')
p1.formerTeams.append('Barcelona')
p2 = Player('Steve')
p2.formerTeams.append('Chelsea')

print("Name:",p1.name)
print("Team Name:",p1.teamName)
print(p1.formerTeams)
print("Name:",p2.name)
print("Team Name:",p2.teamName)
print(p2.formerTeams)

and here you said “used class variable smartly” but it is still can be accessed by any instance of class

class Player:
  teamName = 'Liverpool'      # class variables
  teamMembers = []    
  def __init__(self, name):
    self.name = name        # creating instance variables
    self.formerTeams = []
    self.teamMembers.append(self.name) 

p1 = Player('Mark')
p2 = Player('Steve')

print("Name:",p1.name)
print("Team Members:")
print(p1.teamMembers)
print("")
print("Name:",p2.name)
print("Team Members:")
print(p2.teamMembers)

p3 = Player('John doe')
print(p3.teamMembers)
p3.teamMembers.remove('Mark')
print(p3.teamMembers)

This is Waleed from Educative. Thank you for reaching out to us!

Class variables are shared by all instances of a class. In the first code, ALL instances of the class Player share the class variable formerTeams. Since each player has a distinct former team, it does not make sense to have one variable shared by all players.

Instance variables are unique for each instance of a class. In the second code, each instance of the class Player has its own instance variable formerTeams. Since each player has a distinct former team, it makes sense to have a unique variable for each player.

Best Regards,
Waleed Khalid | Developer Advocate
Educative

you just tell me in 2nd case …
isn’t that class variable accessible by all any instance of class ? just like in the first case?

Yes, in the second case, the class variables teamName and teamMembers can be accessed by all instances of the class.