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
Instrucciones del ejercicio
- Crea dos objetos
Player:p1yp2, con las posiciones9y5respectivamente. - Imprime
p1.MAX_POSITIONyp2.MAX_POSITION. - Asigna
7ap1.MAX_POSITION. - Vuelve a imprimir
p1.MAX_POSITIONyp2.MAX_POSITION.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el 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
____
____