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
This exercise is part of the course
Introduction to Object-Oriented Programming in Python
Exercise instructions
- Create two
Player
objects:p1
andp2
, with positions of9
and5
respectively. - Print
p1.MAX_POSITION
andp2.MAX_POSITION
. - Assign
7
top1.MAX_POSITION
. - Print
p1.MAX_POSITION
andp2.MAX_POSITION
again.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create Players p1 and p2
p1 = ____
p2 = ____
print("MAX_POSITION of p1 and p2 before assignment:")
# Print p1.MAX_POSITION and p2.MAX_POSITION
____
____
# Assign 7 to p1.MAX_POSITION
____
print("MAX_POSITION of p1 and p2 after assignment:")
# Print p1.MAX_POSITION and p2.MAX_POSITION
____
____