1. Learn
  2. /
  3. Courses
  4. /
  5. Introduction to Object-Oriented Programming in Python

Connected

Exercise

Changing class attributes

You learned how to define class attributes and how to access them from class instances. So what will happen if you try to assign another value to a class attribute when accessing it from an instance?

The Player class from the previous exercise has been pre-defined, as shown below:

class Player:
    MAX_POSITION = 10
    def __init__(self, position):
        if position <= Player.MAX_POSITION:
              self.position = position
        else:
              self.position = Player.MAX_POSITION

Instructions

100 XP
  • Create two Player objects: p1 and p2, with positions of 9 and 5 respectively.
  • Print p1.MAX_POSITION and p2.MAX_POSITION.
  • Assign 7 to p1.MAX_POSITION.
  • Print p1.MAX_POSITION and p2.MAX_POSITION again.