Chapter Review Questions

Chapter Review Questions#

Note

Source: Adapted from the C# edition (classes/reviewclasses.rst). Questions updated for Python syntax: __init__ replaces constructors, self replaces this, dunder methods replace operator overloading.

  1. What is the difference between a class and an instance of a class?

  2. What is __init__ and when is it called?

  3. The self parameter.

    1. Why does every instance method have self as its first parameter?

    2. Do you pass self explicitly when calling a method?

  4. Instance variables vs. local variables.

    1. What is an instance variable?

    2. What is a local variable inside a method?

    3. How long does each live?

  5. The __str__ method.

    1. What should __str__ return?

    2. When does Python call it automatically?

  6. What is the difference between __str__ and __repr__?

  7. Given a class Dog with __init__(self, name, breed), write the line that creates a Dog named "Rex" of breed "Lab".

  8. What Python convention signals that an attribute is intended to be private (not accessed from outside the class)?

  9. In the Rational class, __add__ is defined. What expression in user code triggers a call to __add__?

  10. The @dataclass decorator.

    1. What does @dataclass generate automatically?

    2. What does it not generate?

  11. When would you prefer @dataclass(frozen=True) over a plain @dataclass?

  12. What is composition in object-oriented design? Give a one-sentence example.