educative.io

https://www.educative.io/module/lesson/learn-oop-in-python/g2lxBnDomZ3

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)

For the above code, why do we only define the name property in the initializer when more instance variables are mentioned inside?


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

Hello,

The code above shows how the class variables are useful when implementing properties that should be common and accessible to all class objects. The variables used in the initializer function are for player’s name. We are only showing the example how can we use the class variable using player’s name. We can also do this:

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

p1 = Player(‘Mark’,‘Barcelona’)
p2 = Player(‘Steve’,‘Chelsea’)
print(“Name:”, p1.name)
print(“Team Members:”)
print(p1.teamMembers)
print(“Former team”)
print(p1.formerTeams)
print("")
print(“Name:”, p2.name)
print(“Team Members:”)
print(p2.teamMembers)
print(“Former team”)
print(p2.formerTeams)

We can also add other variables using the same conventions.

Hello,
Shouldn’t we use Player.teamMembers.append(self.name) instead of self.teamMembers.append(self.name) in the init method to refer to the class instance variable?
Thanks

You can use either Player.teamMembers.append(self.name) or self.teamMembers.append(self.name) in the __init__ method, and it will work the same way. However, it’s more common and idiomatic to use self.teamMembers to make it clear that you’re working with an instance variable.