Chapter 10, Object-Oriented Programming 15
10.8.1 Base Class CommissionEmployee
No questions.
10.8.2 Subclass SalariedCommissionEmployee
10.8 Q2: Which of the following statements is false?
a. Python provides two built-in functions—issubclass and isinstance—for
testing “is a” relationships.
b. Function issubclass determines whether one class inherits from another.
c. Function isinstance determines whether an object has an “is a” relationship
with a specific type.
d. If SalariedCommissionEmployee inherits from CommissionEmployee, and
if object s is a SalariedCommissionEmployee, then the following snippet re-
sults are correct:
In [19]: isinstance(s, CommissionEmployee)
Out[19]: False
In [20]: isinstance(s, SalariedCommissionEmployee)
Out[20]: True
10.8.3 Processing CommissionEmployees and
SalariedCommissionEmployees Polymorphically
10.8 Q3: Which of the following statements a), b) or c) is false?
a. With inheritance, every object of a subclass also may be treated as an object of
that subclass’s base class.
b. We can take advantage of this “subclass–object-is-a-base-class-object” relation-
ship to place objects related through inheritance into a list, then iterate through
the list and treat each element as a base-class object.
c. The following code places CommissionEmployee and SalariedCommis-
sionEmployee objects (c and s) in a list, then for each element displays its string
representation and earnings—this is an example of polymorphism:
In [21]: employees = [c, s]
In [22]: for employee in employees:
…: print(employee)
…: print(f‘{employee.earnings():,.2f}\n’)
…:
16 Chapter 10, Object-Oriented Programming
CommissionEmployee: Sue Jones
social security number: 333–33-3333
gross sales: 20000.00
commission rate: 0.10
2,000.00
SalariedCommissionEmployee: Bob Lewis
social security number: 444–44-4444
gross sales: 10000.00
commission rate: 0.05
base salary: 1000.00
1,500.00
d. All of the above statements are true.
10.8.4 A Note About Object-Based and Object-Oriented Programming
No questions.
10.9 Duck Typing and Polymorphism
10.9 Q1: Which of the following statements a), b) or c) is false?
b. All classes inherit from object directly or indirectly, so they all inherit the de-
fault methods for obtaining string representations that print can display.
b. Python also has duck typing, which the Python documentation describes as:
A programming style which does not look at an object’s type to determine
if it has the right interface; instead, the method or attribute is simply called
or used (“If it looks like a duck and quacks like a duck, it must be a duck.”).
c. When Python processes an object at execution time, its type does not matter.
As long as the object has the data attribute, property or method (with the appro-
priate parameters) you wish to access, the code will work.
d. All of the above statements are true.
10.9 Q2: Consider the following loop, which processes a list of employees:
for employee in employees:
print(employee)
print(f‘{employee.earnings():,.2f}\n’)
Chapter 10, Object-Oriented Programming 17
Which of the following statements a), b) or c) is false?
a. In Python, this loop works properly as long as employees contains only objects
that can be displayed with print (that is, they have a string representation)
b. All classes inherit from object directly or indirectly, so they all inherit the de-
fault methods for obtaining string representations that print can display.
c. If a class has an earnings method that can be called with no arguments, we
can include objects of that class in the list employees, even if the object’s class
does not have an “is a” relationship with class CommissionEmployee.
d. All of the above statements are true.
10.10 Operator Overloading
10.10 Q1: Which of the following statements a), b) or c) is false?
a. You use operator overloading to define how Python’s operators should handle
objects of your own custom types.
b. The overloaded + operator is used for adding numeric values, concatenating
lists, concatenating strings and adding a value to every element in a NumPy array.
c. The overloaded [] operator is used for accessing elements in lists, tuples,
strings and arrays and for accessing the value for a specific key in a dictionary.
The overloaded * operator is used for multiplying numeric values, repeating a se-
quence and multiplying every element in a NumPy array by a specific value.
d. All of the above statements are true.
10.10 Q2: Which of the following statements a), b) or c) is false?
a. You can overload most operators.
b. For every overloadable operator, class object defines a special method, such
as _add_ for the addition (+) operator or _mul_ for the multiplication (*) opera-
tor.
c. Overriding operator special methods enables you to define how a given opera-
tor works for objects of your custom classes.
d. All of the above statements are true.
18 Chapter 10, Object-Oriented Programming
© Copyright 2020 by Pearson Education, Inc. All Rights Reserved.
Answer: b. Actually, each of these special methods begins and ends with
double underscores, so the method names are __add__ for the addition (+)
operator and __mul__ for the multiplication (*) operator.
10.10 Q3: Which of the following statements is false?
a. The precedence of an operator cannot be changed by overloading. As in algebra,
parentheses can be used to force evaluation order of operators in an expression.
b. The left–to-right or right-to-left grouping of an operator cannot be changed by
overloading. The “arity” of an operator—that is, whether it’s a unary or binary
operator—cannot be changed. You cannot create new operators—only existing
operators can be overloaded.
c. The meaning of how an operator works on objects of built-in types cannot be
changed—you cannot, for example, change + so that it subtracts two integers.
d. Operator overloading works only with objects of custom classes.
10.10.1 Test-Driving Class Complex
No questions.
10.10.2 Class Complex Definition
No questions.
10.11 Exception Class Hierarchy and Custom Exceptions
10.11 Q1: Exception classes inherit directly or indirectly from base class
BaseException and are defined in module exceptions. Python defines four
primary BaseException subclasses—SystemExit, KeyboardInterrupt, Gen-
eratorExit and Exception. Which of the following statements a), b) or c) is
false?
a. SystemExit terminates program execution (or terminates an interactive ses-
sion) and when uncaught does not produce a traceback like other exception
types.
b. KeyboardInterrupt exceptions occur when the user types the interrupt com-
mand—Ctrl + C (or control + C) on most systems.
c. GeneratorExit exceptions occur when a generator closes—normally when a
generator finishes producing values or when its close method is called explicitly.
Exception is the base class for most common exceptions you’ll encounter.
Chapter 10, Object-Oriented Programming 19
d. All of the above statements are true.
10.11 Q2: Which of the following statements a), b) or c) is false?
a. One of the benefits of the exception class hierarchy is that an except handler
can catch exceptions of a particular type or can use a base-class type to catch
those base-class exceptions and all related subclass exceptions.
b. An except handler that specifies the base class Exception can catch objects
of any subclass of Exception.
c. An except handler that catches type Exception should be placed before other
except handlers to ensure that all exceptions are properly caught by their spe-
cific type of exception.
d. All of the above statements are true.
10.12 Named Tuples
10.12 Q1: Which of the following statements a), b) or c) is false?
a. The Python Standard Library’s collections module also provides named tu-
ples that enable you to reference a tuple’s members by name rather than by index
number.
b. Function namedtuple creates a base class of the built-in tuple type.
c. The function’s first argument is your new type’s name and the second is a list
of strings representing the identifiers you’ll use to reference the new type’s mem-
bers—for example.
In [2]: Card = namedtuple(‘Card’, [‘face’, ‘suit’])
d. All of the above statements are true.
10.12 Q2: Which of the following statements a), b) or c) is false?
a. Each named tuple type has additional methods.
b. The type’s _make class method (that is, a method called on the class) receives
an iterable of values and returns an object of the named tuple type. For example:
20 Chapter 10, Object-Oriented Programming
In [7]: values = [‘Queen’, ‘Hearts’]
In [8]: card = Card._make(values)
In [9]: card
Out[9]: Card(face=’Queen’, suit=‘Hearts‘)
c. For a given object of a named tuple type, you can get an OrderedDict diction-
ary representation of the object’s member names and values—an OrderedDict
remembers the order in which its key–value pairs were inserted in the dictionary.
d. All of the above statements are true.
10.13 A Brief Intro to Python 3.7’s New Data Classes
10.13 Q1: Which of the following statements is false?
a. Though named tuples allow you to reference their members by name, they’re
still just tuples, not classes.
b. For some of the benefits of named tuples, plus the capabilities that traditional
Python classes provide, you can use Python 3.7’s data classes from the Python
Standard Library’s dataclasses module.
c. One problem with data classes is that they typically require more development
time than traditional classes.
d. Data classes could become the preferred way to define many Python classes.
10.13 Q2: Which of the following statements is false?
a. Most classes you’ll define provide an __init__ method to create and initialize
an object’s attributes and a __repr__ method to specify an object’s custom string
representation.
b. Data classes also autogenerate method __eq__, which overloads the = opera-
tor.
c. Any class that has an __eq__ method also implicitly supports !=.
d. All classes inherit class object’s default __ne__ (not equals) method imple-
mentation, which returns the opposite of __eq__ (or NotImplemented if the
class does not define __eq__).
22 Chapter 10, Object-Oriented Programming
: ClassVar[List[str]]
is a variable annotation (sometimes called a type hint) specifying that FACES and
SUITS are class attributes (ClassVar) which refers to a list of strings
(List[str]). Class variables are initialized in their definitions and are specific to
the class, not individual objects of the class.
10.13 Q6: Which of the following statements a), b) or c) is false?
a. You can specify variable annotations using built-in type names (like str, int
and float), class types or types defined by the typing module (such as
ClassVar and List).
b. Even with type annotations, Python is still a dynamically typed language.
c. Type annotations are not enforced at execution time.
d. All of the above statements are true.
10.13.2 Using the Card Data Class
No questions.
10.13.3 Data Class Advantages over Named Tuples
10.13 Q7: Data classes offer several advantages over named tuples. Which of the
following statements a), b) or c) is false?
a. Although each named tuple technically represents a different type, a named tu-
ple is a tuple and all tuples can be compared to one another. So, objects of differ-
ent named tuple types could compare as equal if they have the same number of
members and the same values for those members. Comparing objects of different
data classes always returns False, as does comparing a data class object to a tu-
ple object.
b. If you have code that unpacks a tuple, adding more members to that tuple
breaks the unpacking code. Data class objects cannot be unpacked. So you can add
more data attributes to a data class without breaking existing code.
c. A data class can be a base class or a subclass in an inheritance hierarchy.
d. All of the above statements are true.
Chapter 10, Object-Oriented Programming 25
b. The local namespace exists from the moment the function or method is called
until it terminates and is accessible only to that function or method.
c. In a function’s or method’s suite, assigning to a variable that does not exist cre-
ates a local variable and adds it to the local namespace.
d. Identifiers in the local namespace are in scope from the point at which you de-
fine them until the program terminates.
10.15 Q3: Which of the following statements a), b) or c) is false?
a. Each module has a global namespace that associates a module’s global identifi–
ers (such as global variables, function names and class names) with objects. An
IPython session has its own global namespace for all the identifiers you create in
that session.
b. Python creates a module’s global namespace when it loads the module. A mod-
ule’s global namespace exists and its identifiers are in scope to the code within
that module until the program (or interactive session) terminates.
c. Each module’s global namespace also has an identifier called __name__ con-
taining the module’s name, such as ‘math’ for the math module.
d. All of the above statements are true.
10.15 Q4: When you use an identifier, Python searches for that identifier in the
currently accessible namespaces, proceeding from ________ to ________ to ________.
a. global, built-in, local
b. built-in, local, global
c. local, built-in, global
d. local, global, built-in
10.15 Q5: Which of the following statements a), b) or c) is false?
a. Python allows you to define nested functions inside other functions or methods.
b. If a function or method performs the same task several times, you might define
a nested function to avoid repeating code in the enclosing function.
c. When you access an identifier inside a nested function, Python searches the
nested function’s local namespace first, then the global namespace, then the built–
in namespace and finally the enclosing function’s namespace —this is sometimes
referred to as the LGBE (local, global, built-in, enclosing) rule.
d. All of the above statements are true.
© Copyright 2020 by Pearson Education, Inc. All Rights Reserved.
10.15 Q6: Which of the following statements a), b) or c) is false?
a. Each object has its own namespace containing the object’s methods and data
attributes.
b. The class’s __init__ method starts with an empty object (self) and adds each
attribute to the object’s namespace.
c. Once you define an attribute in an object’s namespace, clients using the object
may access the attribute’s value.
d. All of the above statements are true.
10.16 Intro to Data Science: Time Series and Simple Linear
Regression
10.16 Q1: Which of the following statements a), b) or c) is false?
a. Time series are sequences of values called observations associated with points
in time.
b. Some examples of time series are daily closing stock prices, hourly temperature
readings, the changing positions of a plane in flight, annual crop yields, quarterly
company profits, and the stream of time-stamped tweets coming from Twitter
users worldwide.
c. You can use simple linear regression to make predictions from time series data.
d. All of the above statements are true.
10.16 Q2: ________ time series have one observation per time, such as the average
of the January high temperatures in New York City for a particular year; ________
time series have two or more observations per time, such as temperature, humid-
ity and barometric pressure readings in a weather application.
a. Univariate, bivariate
b. Single, multivariate
c. Univariate, multivariate
d. Single, mixed