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.
What is the difference between a class and an instance of a class?
What is
__init__and when is it called?The
selfparameter.Why does every instance method have
selfas its first parameter?Do you pass
selfexplicitly when calling a method?
Instance variables vs. local variables.
What is an instance variable?
What is a local variable inside a method?
How long does each live?
The
__str__method.What should
__str__return?When does Python call it automatically?
What is the difference between
__str__and__repr__?Given a class
Dogwith__init__(self, name, breed), write the line that creates aDognamed"Rex"of breed"Lab".What Python convention signals that an attribute is intended to be private (not accessed from outside the class)?
In the
Rationalclass,__add__is defined. What expression in user code triggers a call to__add__?The
@dataclassdecorator.What does
@dataclassgenerate automatically?What does it not generate?
When would you prefer
@dataclass(frozen=True)over a plain@dataclass?What is composition in object-oriented design? Give a one-sentence example.