Implementar lógica para atributos
La clase Player que creaste antes fue un buen comienzo, pero una de las ventajas clave de los atributos a nivel de clase es su capacidad para restringir los límites superior y/o inferior de los datos.
En este ejercicio, vas a modificar la definición de la clase Player para impedir que el valor de position supere el valor MAX_POSITION definido a nivel de clase.
Este ejercicio forma parte del curso
Introducción a la programación orientada a objetos en Python
Instrucciones del ejercicio
- 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.
ejercicio interactivo práctico
Prueba este ejercicio completando este código de ejemplo.
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(____.____)