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 de ejercicio
- Crea dos objetos
Player
:p1
yp2
, con las posiciones9
y5
respectivamente. - Imprime
p1.MAX_POSITION
yp2.MAX_POSITION
. - Asigna
7
ap1.MAX_POSITION
. - Vuelve a imprimir
p1.MAX_POSITION
yp2.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
____
____