Practice Exercises for Python Classes and Objects

Practice Exercises for Python Classes and Objects

These are the companion exercises to the article, Python Classes Zero to Expert.

1. The code below has two bugs. Can you spot them? Try to do it without running the code.

class Pet:
    def init(self, name):
        self.name = name
        
    def move():
        return f"{self.name} is moving..."

2. Rewrite the code from the last question so that the test below works and prints “Fritz is moving…”

# Paste and fix the code here:

# Leave this code
dog = Pet("Fritz")
print(dog.move())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [1], in <cell line: 4>()
      1 # Paste and fix the code here:
      2 
      3 # Leave this code
----> 4 dog = Pet("Fritz")
      5 print(dog.move())

NameError: name 'Pet' is not defined

3. Write a simple Tag class to encapsulate HTML tags, for example,

<p>I am a paragraph.</p>

The constructor should save the text to be wrapped in the HTML tag, and the render method should return the text wrapped in the opening and closing HTML tag. Using inheritance, create subclasses for Paragraph (tag is as above) and ListItem (tag looks like <li>I am a list item</li>).

4. For the tag class hierarchy, can you think of how this might be implemented as a function? Which way would you think is simpler and more maintainable?

5. Create an abstract base class, Shape, with a single abstract method, draw. Implement two child classes, Elipse and Rectangle, that override the draw method. For the implementation, you can substitute a stub (a simple string printout saying what the class is drawing).

6. You will need to create an init method with some data for this task. For the Rectangle class that you defined above, print a rectangle using characters and the code to test it, for example:

# ... Implementation code above:

r = Rectangle(5,3)
r.draw()
*****
*****
*****

7. Modify the Rectangle class to make the character that gets printed configurable, but with a default of X. Write code to test it.

8. Create Square as a subclass of Rectangle, which does the right thing for a square. Change the default value of the character to %But continue to allow it to be overridden.

9. For each of the classes created above in exercises 5-8, implement a reasonable __str__ method and test.

10. For each of the classes created above in exercises 5-8, implement a reasonable __repr__ method and test.