1

I'm trying to use class objects in a list for the first time. But for some reason, the attributes of all class objects in the list are getting assigned the same value as the last object in the list. Here's my code:

# First I define the class
class Batsman:
   def __init__(self, innings, avg, sr):
       Batsman.innings = innings
       Batsman.avg = avg
       Batsman.sr = sr

# Then I create the list of class objects:
batsman = [
        Batsman(100,45,65),
        Batsman(50,40,60)
]

# Then I print the below:

print(batsman[0].innings)

Output should be 100, but it is 50 instead. Why is this? If I use 5 instances, the attributes of all 5 get reset to whatever the last object contains. Why is this?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
oktested
  • 81
  • 1
  • 7
  • If it is a **class** attribute, why should it differ for different **instances**? – user2390182 Nov 07 '18 at 10:16
  • 1
    Possible duplicate of [python: What happens when class attribute, instance attribute, and method all have the same name?](https://stackoverflow.com/questions/12949064/python-what-happens-when-class-attribute-instance-attribute-and-method-all-ha) – mx0 Nov 07 '18 at 10:20

1 Answers1

2

When using the name of the class Batsman you are refering to the class not the instance, you need to use self:

class Batsman:
   def __init__(self, innings, avg, sr):
       self.innings = innings
       self.avg = avg
       self.sr = sr

# Then I create the list of class objects:
batsman = [
        Batsman(100,45,65),
        Batsman(50,40,60)
]

# Then I print the below:

print(batsman[0].innings)

You can check some extra explanations and inforamtion about self in this other question

Netwave
  • 40,134
  • 6
  • 50
  • 93