EmpezarEmpieza gratis

Cambiar atributos de clase

Has aprendido a definir atributos de clase y a acceder a ellos desde las instancias. Entonces, ¿qué ocurre si intentas asignar otro valor a un atributo de clase cuando lo accedes desde una instancia?

La clase Player del ejercicio anterior está predefinida, como se muestra a continuación:

class Player:
    MAX_POSITION = 10
    def __init__(self, position):
        if position <= Player.MAX_POSITION:
              self.position = position
        else:
              self.position = Player.MAX_POSITION

Este ejercicio forma parte del curso

Introducción a la programación orientada a objetos en Python

Ver curso

Instrucciones del ejercicio

  • Crea dos objetos Player: p1 y p2, con posiciones 9 y 5, respectivamente.
  • Imprime p1.MAX_POSITION y p2.MAX_POSITION.
  • Asigna 7 a p1.MAX_POSITION.
  • Vuelve a imprimir p1.MAX_POSITION y p2.MAX_POSITION.

ejercicio interactivo práctico

Prueba este ejercicio completando este código de ejemplo.

# Create Players p1 and p2
p1 = ____
p2 = ____

print("MAX_POSITION of p1 and p2 before assignment:")
# Print p1.MAX_POSITION and p2.MAX_POSITION
____
____

# Assign 7 to p1.MAX_POSITION
____

print("MAX_POSITION of p1 and p2 after assignment:")
# Print p1.MAX_POSITION and p2.MAX_POSITION
____
____
Editar y ejecutar código