Chapter 10, Object-Oriented Programming 1
Object-Oriented Programming
10.1 Introduction
10.1 Q1: Which of the following statements a), b) or c) is false?
a. Everything in Python is an object.
b. Just as houses are built from blueprints, classes are built from objects—one of
the core technologies of object-oriented programming.
c. Building a new object from even a large class is simple—you typically write one
statement.
d. All of the above statements are true.
10.1 Q2: Which of the following statements a), b) or c) is false?
a. You’ll use lots of classes created by other people.
b. You can create your own custom classes.
c. Core technologies of object-oriented programming are classes, objects, inher-
itance and polymorphism.
d. All of the above statements are true.
10.1 Q3: Which of the following statements is false?
a. The vast majority of object–oriented programming you’ll do in Python is object–
based programming in which you primarily use objects of new custom classes
you create.
b. To take maximum advantage of Python you must familiarize yourself with lots
of preexisting classes.
c. Over the years, the Python open-source community has crafted an enormous
number of valuable classes and packaged them into class libraries, available on
the Internet at sites like GitHub, BitBucket, SourceForge and more. This makes it
easy for you to reuse existing classes rather than “reinventing the wheel.”
d. Widely used open-source library classes are more likely to be thoroughly
tested, bug free, performance tuned and portable across a wide range of devices,
operating systems and Python versions.
10.1 Q4: Which of the following statements a), b) or c) is false?
2 Chapter 10, Object-Oriented Programming
a. Classes are new function types.
b. Most applications you’ll build for your own use will commonly use either no
custom classes or just a few.
c. You can contribute your custom classes to the Python open-source community,
but you are not obligated to do so. Organizations often have policies and proce-
dures related to open-sourcing code.
d. All of the above statements are true.
10.1 Q5: Which of the following statements is false?
a. New classes can be formed quickly through inheritance and composition from
classes in abundant class libraries.
b. Eventually, software will be constructed predominantly from standardized, re-
usable components, just as hardware is constructed from interchangeable parts
today. This will help meet the challenges of developing ever more powerful soft-
ware.
c. When creating a new class, instead of writing all new code, you can designate
that the new class is to be formed initially by inheriting the attributes and meth-
ods of a previously defined base class (also called a subclass) and the new class is
called a derived class (or superclass).
d. After inheriting, you then customize the derived class to meet the specific needs
of your application. To minimize the customization effort, you should always try
to inherit from the base class that’s closest to your needs.
10.1 Q6: Which of the following statements a), b) or c) is false?
a. Polymorphism enables you to conveniently program “in the general” rather
than “in the specific.”
b. With polymorphism, you simply send the same method call to objects possibly
of many different types. Each object responds by “doing the right thing” for ob-
jects of its type. So the same method call takes on many forms, hence the term
“poly–morphism.”
c. In Python, as in other major object-oriented programming languages, you can
implement polymorphism only via inheritance.
d. All of the above statements are true.
4 Chapter 10, Object-Oriented Programming
account1.deposit(Decimal(‘25.53’))
account1.balance
d. All of the above statements are true.
10.2.2 Account Class Definition
10.2 Q4: Which of the following statements is false?
a. A class definition begins with the keyword class followed by the class’s name
and a colon (:). This line is called the class header.
b. The Style Guide for Python Code recommends that you begin each word in a
multi-word class name with an uppercase letter (e.g., CommissionEmployee).
c. Every statement in a class’s suite is indented.
d. Each class must provide a descriptive docstring in the line or lines immediately
following the class header. To view any class’s docstring in IPython, type the class
name and a question mark, then press Enter.
10.2 Q5: Which of the following statements is false?
a. The following constructor expression creates a new object, then initializes its
data by calling the class’s __init__ method:
account1 = Account(‘John Green’, Decimal(‘50.00′))
b. Each new class you create can provide an __init__ method that specifies how
to initialize an object’s data attributes.
c. Returning a value other than Null from __init__ results in a TypeError.
Null is returned by any function or method that does not contain a return state-
ment.
d. Class Account’s __init__ method below initializes an Account object’s name
and balance attributes if the balance is valid:
def __init__(self, name, balance):
“””Initialize an Account object.”””
# if balance is less than 0.00, raise an exception
if balance < Decimal(‘0.00’):
raise ValueError(‘Initial balance must be >= to 0.00.’)
self.name = name
Chapter 10, Object-Oriented Programming 5
self.balance = balance
10.2 Q6: Which of the following statements a), b) or c) is false?
a. When you call a method for a specific object, Python implicitly passes a refer-
ence to that object as the method’s first argument, so all methods of a class must
specify at least one parameter.
b. All methods must have a first parameter self—a class’s methods must use that
reference to access the object’s attributes and other methods.
c. When an object of a class is created, it does not yet have any attributes. They’re
added dynamically via assignments, typically of the form self.attribute_name =
value.
d. All of the above statements are true.
10.2 Q7: Python class ________ defines the special methods that are available for
all Python objects.
a. object
b. special
c. class
d. root
10.2.3 Composition: Object References as Members of Classes
10.2 Q8: An object’s attributes are references to objects of other classes. Embed–
ding references to objects of other classes is a form of software reusability known
as ________ and is sometimes referred to as the ________ relationship.
a. composition, “is a”
b. inheritance, “has a”
c. composition, “has a”
d. inheritance, “is a”
Chapter 10, Object-Oriented Programming 7
b. An attribute name beginning with an underscore (_) is never accessible by cli-
ents of a class.
c. Client code should use the class’s methods and properties to interact with each
object’s internal-use data attributes.
d. All of the above statements are true.
10.4 Properties for Data Access
10.4 Q1: Properties look like ________ to client-code programmers, but control the
manner in which they get and modify an object’s data.
a. function calls
b. method calls
c. data attributes
d. None of the above
10.4.1 Test-Driving Class Time
10.4 Q2: Assume that class Time’s __init__ method receives hour, minute and
second parameters. Based on the following code:
wake_up = Time(hour=6, minute=30)
which of the following statements is true?
a. If at least two arguments have default arguments, the third automatically de-
faults to zero.
b. Any omitted argument is automatically set to zero.
c. second has a default argument in the __init__ method’s definition.
d. None of the above.
10.4 Q3: When you evaluate a variable in IPython it calls the corresponding ob-
ject’s ________ special method to produce a string representation of the object.
a. __init__
b. __str__
c. __string__
d. __repr__
Chapter 10, Object-Oriented Programming 9
a. The code attempts to set the hour property to an invalid value.
b. The code checks that the hour property is in the range 0 through 24.
c. The value 100 is out of range so the code raises a ValueError.
d. All of the above statements are true.
10.4.2 Class Time Definition
10.4 Q7: Consider the following class Time __init__ method:
def __init__(self, hour=0, minute=0, second=0):
“””Initialize each attribute.”“”
self.hour = hour # 0–23
self.minute = minute # 0–59
self.second = second # 0–59
Which of the following statements a), b) or c) is false?
a. Class Time’s __init__ method specifies hour, minute and second parame-
ters, each with a default argument of 0.
b. The self parameter is a reference to the Time object being initialized.
c. The statements containing self.hour, self.minute and self.second ap-
pear to create hour, minute and second attributes for the new Time object
(self). However, these statements may actually call methods that implement the
class’s hour, minute and second properties.
d. All of the above statements are true.
10.4 Q8: Consider the following code from our class Time:
@property
def hour(self):
“””Return the hour.”””
return self._hour
@hour.setter
def hour(self, hour):
“””Set the hour.”””
if not (0 <= hour < 24):
raise ValueError(f‘Hour ({hour}) must be 0-23′)
self._hour = hour
10 Chapter 10, Object-Oriented Programming
a. This code defines a read-write property named hour that manipulates a data
attribute named _hour.
b. The single-leading-underscore (_) naming convention indicates that client
code can safely access _hour directly.
c. Properties look like data attributes to programmers working with objects.
Properties are implemented as methods.
d. All of the above statements are true.
10.4 Q9: Which of the following statements a), b) or c) is false?
a. Each property defines a getter method which gets (that is, returns) a data at-
tribute’s value and can optionally define a setter method which sets a data attrib-
ute’s value.
b. The @property decorator precedes a property’s getter method, which receives
only a self parameter.
c. Behind the scenes, a decorator adds code to the decorated function to enable
the function to work with data attribute syntax.
d. All of the above statements are true.
10.4 Q10: A read-only property has ________.
a. only a setter
b. only a getter
c. a setter and a getter
d. neither a setter nor a getter
10.4 Q11: Which of the following statements a), b) or c) is false?
a. When you pass an object to built-in function repr—which happens implicitly
when you evaluate a variable in an IPython session—the corresponding class’s
__repr__ special method is called to get the “official” string representation of the
object.
b. Typically the string returned by __repr__ looks like a constructor expression
that creates and initializes the object, such as:
‘Time(hour=6, minute=30, second=0)‘
Chapter 10, Object-Oriented Programming 11
c. Python has a built-in function eval that could receive the string shown in Part
(b) as an argument and use it to create and initialize a Time object containing
values specified in the string.
d. All of the above statements are true.
10.4 Q12: The ________ special method is called implicitly when you convert an
object to a string with the built-in function str, such as when you print an object
or call str explicitly.
a. __repr__
b. __string__
c. __str__
d. None of the above
10.4.3 Class Time Definition Design Notes
10.4 Q13: Class Time’s properties and methods define the class’s ________ inter-
face, that is, the properties and methods programmers should use to interact with
objects of the class.
a. public
b. private
c. protected
d. None of the above
10.4 Q14: Which of the following statements a), b) or c) is false?
a. When you design a class, carefully consider the class’s interface before making
that class available to other programmers.
b. Unfortunately, existing code will break if you update the class’s implementation
details—that is, the internal data representation or how its method bodies are
implemented.
c. If Python programmers follow convention and do not access attributes that
begin with leading underscores, then class designers can evolve class implemen-
tation details without breaking client code.
d. All of the above statements are true.
Chapter 10, Object-Oriented Programming 13
d. IPython does not show attributes with one or two leading underscores when
you try to auto-complete an expression like
wake_up.
by pressing Tab. Only attributes that are part of the wake_up object’s “public” in-
terface are displayed in the IPython auto-completion list.
10.6 Case Study: Card Shuffling and Dealing Simulation
No questions.
10.6.1 Test-Driving Classes Card and DeckOfCards
No questions.
10.6.2 Class Card—Introducing Class Attributes
10.6 Q1: Which of the following statements is false?
a. Sometimes, an attribute should be shared by all objects of a class. A class attrib-
ute (also called a class variable) represents class-wide information—it belongs to
the class, not to a specific object of that class.
b. You define a class attribute by assigning a value to it inside the class’s definition,
but not inside any of the class’s methods or properties (in which case, they’d be
local variables).
c. Class attributes are typically accessed through any object of the class.
d. Class attributes exist as soon as you import their class’s definition.
10.6.3 Class DeckOfCards
No questions.
10.6.4 Displaying Card Images with Matplotlib
No questions.