ComeçarComece gratuitamente

Alteração de atributos de classe

Você aprendeu como definir atributos de classe e como acessá-los a partir de instâncias de classe. Então, o que acontecerá se você tentar atribuir outro valor a um atributo de classe ao acessá-lo a partir de uma instância?

A classe Player do exercício anterior foi predefinida, conforme mostrado abaixo:

class Player:

    MAX_POSITION = 10

    def __init__(self, position):

        if position <= Player.MAX_POSITION:

              self.position = position

        else:

              self.position = Player.MAX_POSITION

Este exercício faz parte do curso

Introdução à programação orientada a objetos em Python

Ver Curso

Instruções de exercício

  • Crie dois objetos Player: p1 e p2, com as posições 9 e 5, respectivamente.
  • Imprima p1.MAX_POSITION e p2.MAX_POSITION.
  • Atribua 7 a p1.MAX_POSITION.
  • Imprima p1.MAX_POSITION e p2.MAX_POSITION novamente.

Exercício interativo prático

Experimente este exercício preenchendo este código de exemplo.

# 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 e executar código