Implementing logic for attributes
The Player
class you previously created was a good start, but one of the key benefits of class-level attributes is their ability to restrict the upper and/or lower boundaries of data.
In this exercise, you'll modify the Player
class definition to restrict the value of position
from going above the class-level MAX_POSITION
value.
This exercise is part of the course
Introduction to Object-Oriented Programming in Python
Exercise instructions
- Define the
__init__()
constructor with two arguments,self
andposition
. - Inside the constructor, check if
position
is less than or equal to the class-levelMAX_POSITION
; if so, assignposition
toself.position
- If
position
is more than the class-levelMAX_POSITION
, assign it to the class'.MAX_POSITION
attribute. - Create a
Player
objectp
with a position of6
and print itsMAX_POSITION
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
class Player:
MAX_POSITION = 10
# Define a constructor
____ ____(____, ____):
# Check if position is less than the class-level attribute value
if ____ <= ____.____:
____.____ = ____
# If not, set equal to the class-level attribute
else:
____.____ = ____.____
# Create a Player object, p, and print its MAX_POSITITON
p = ____(____)
print(____.____)