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,selfandposition. - Inside the constructor, check if
positionis less than or equal to the class-levelMAX_POSITION; if so, assignpositiontoself.position - If
positionis more than the class-levelMAX_POSITION, assign it to the class'.MAX_POSITIONattribute. - Create a
Playerobjectpwith a position of6and 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(____.____)