EmpezarEmpieza gratis

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

Ver curso

Instrucciones del ejercicio

  • 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.

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(____.____)
Editar y ejecutar código