Python: understanding class and instance variables

The trick here is in understanding what self.energy -= 1 does. It’s really two expressions; one getting the value of self.energy - 1, and one assigning that back to self.energy.

But the thing that’s confusing you is that the references are not interpreted the same way on both sides of that assignment. When Python is told to get self.energy, it tries to find that attribute on the instance, fails, and falls back to the class attribute. However, when it assigns to self.energy, it will always assign to an instance attribute, even though that hadn’t previously existed.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)