Aan de slagGa gratis aan de slag

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                 

Deze oefening maakt deel uit van de cursus

Introduction to Object-Oriented Programming in Python

Cursus bekijken

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# 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)
Code bewerken en uitvoeren