IniziaInizia gratis

Inheritance of class attributes

Earlier in the course, you learned about class attributes and methods that are shared among all the instances of a class. How do they work with inheritance?

In this exercise, you'll create a subclass of the Player class you worked with earlier in the chapter and explore the inheritance of class attributes and methods.

The Player class has been defined for you, and the code provided here:

class Player:
    MAX_POSITION = 10

    def __init__(self):
      self.position = 0

    def move(self, steps):
      if self.position + steps < Player.MAX_POSITION:
        self.position += steps 
      else:
        self.position = Player.MAX_POSITION                 

Questo esercizio fa parte del corso

Introduction to Object-Oriented Programming in Python

Visualizza il corso

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

# Create a Racer class inheriting from Player
____(____):
  # Create MAX_POSITION with a value of 15
  ____ = ____
  
# Create a Player and a Racer objects
p = ____
r = ____

print("p.MAX_POSITION = ", p.MAX_POSITION)
print("r.MAX_POSITION = ", r.MAX_POSITION)
Modifica ed esegui il codice