MulaiMulai sekarang secara gratis

Changing class attributes

You learned how to define class attributes and how to access them from class instances. So what will happen if you try to assign another value to a class attribute when accessing it from an instance?

The Player class from the previous exercise has been pre-defined, as shown below:

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

Latihan ini adalah bagian dari kursus

Introduction to Object-Oriented Programming in Python

Lihat Kursus

Petunjuk latihan

  • Create two Player objects: p1 and p2, with positions of 9 and 5 respectively.
  • Print p1.MAX_POSITION and p2.MAX_POSITION.
  • Assign 7 to p1.MAX_POSITION.
  • Print p1.MAX_POSITION and p2.MAX_POSITION again.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# 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
____
____
Edit dan Jalankan Kode