Get startedGet started for free

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

View Course

Exercise instructions

  • Define the __init__() constructor with two arguments, self and position.
  • Inside the constructor, check if position is less than or equal to the class-level MAX_POSITION; if so, assign position to self.position
  • If position is more than the class-level MAX_POSITION, assign it to the class' .MAX_POSITION attribute.
  • Create a Player object p with a position of 6 and print its MAX_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(____.____)
Edit and Run Code