ComenzarEmpieza gratis

Cambio de atributos de clase

Has aprendido a definir atributos de clase y a acceder a ellos desde instancias de clase. Entonces, ¿qué ocurrirá si intentas asignar otro valor a un atributo de clase al acceder a él desde una instancia?

Se ha predefinido la clase Player del ejercicio anterior, 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 de ejercicio

  • Crea dos objetos Player: p1 y p2, con las 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

Pruebe este ejercicio completando este código de muestra.

# 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