educative.io

Why use append in initializer but not in the instance of the object?

Hi!!

Why use append inside the initializer and not outside the class when the object is instantiated since the variable teamMembers can be accessed by all objects?

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)

Both of these methods can be used to append to the variable teamMember as it is a class variable. The difference is that if you append it in the initializer, it will be appended to the class variable as soon as the instance of a class is made. However, if you append it outside the class, you will have to append it separately each time for each object.