Every problem in the chapter beside the book’s answer, a chapter at a time as you scroll.

Chapter 11: Classes

38 problems · 0 figures

Concepts in Practice 11.1.1 §11.1 source ↗

Consider the example above. Which is a field in Ellis's 12/18/23 post?
  1. a.
    Ellis's followers list
  2. b.
    Ellis's username
Video · Using objects to model social media in the book ↗

Answer

B. Ellis's username
Ellis's username represents the post creator.

Concepts in Practice 11.1.2 §11.1 source ↗

What does an object typically model in object-oriented programming?
  1. a.
    program code
  2. b.
    real-world entity

Answer

B. real-world entity
An object models a real-world entity with fields and procedures.

Concepts in Practice 11.1.3 §11.1 source ↗

Consider the example above. Suppose the venue has to be changed due to inclement weather. How should a programmer change the website object to allow changes to the Venue field?
  1. a.
    Add a procedure to change the field.
  2. b.
    Allow users direct access to the field.
  3. c.
    No valid way to allow changes to the field.
Video · Encapsulating concert ticket information in the book ↗

Answer

A. Add a procedure to change the field.
A procedure, such as Change venue, can make changes to the field and protect the field from inappropriate access.

Concepts in Practice 11.1.4 §11.1 source ↗

Which is a benefit of encapsulation when developing complex programs?
  1. a.
    All objects can easily access and modify each other's data.
  2. b.
    Each object's data is restricted for intentional access.

Answer

B. Each object's data is restricted for intentional access.
Limiting data access prevents accidental changes and makes relationships between objects clearer.

Concepts in Practice 11.1.5 §11.1 source ↗

Consider the car example in the paragraph above. Suppose the designer decided to remove the engine temperature indicator. Would this be a good use of abstraction?
  1. a.
    yes
  2. b.
    no
Video · Abstracting data in a countdown calculator in the book ↗

Answer

B. no
Correct abstraction makes only necessary information visible. An overheated engine can cause irreparable damage, so an indicator is necessary for the driver.

Concepts in Practice 11.1.6 §11.1 source ↗

Which is a benefit of abstraction?
  1. a.
    improved view of information
  2. b.
    high visibility of information

Answer

A. improved view of information
Showing only the necessary information reduces clutter and improves the overall experience.

Concepts in Practice 11.2.1 §11.2 source ↗

Consider the example below:

class Cat:
  def __init__(self):
    self.name = 'Kitty'
    self.breed = 'domestic short hair'
    self.age = 1
  def print_info(self):
    print(self.name, 'is a ', self.age, 'yr old', self.breed)

pet_1 = Cat()
pet_2 = Cat()
What is the name of the class?
  1. a.
    Cat
  2. b.
    class Cat
  3. c.
    self

Answer

A. Cat
Cat follows the class keyword at the top of the class definition and is the name of the class.

Concepts in Practice 11.2.2 §11.2 source ↗

Consider the example below:

class Cat:
  def __init__(self):
    self.name = 'Kitty'
    self.breed = 'domestic short hair'
    self.age = 1
  def print_info(self):
    print(self.name, 'is a ', self.age, 'yr old', self.breed)

pet_1 = Cat()
pet_2 = Cat()
Which of the following is an instance of the Cat class?
  1. a.
    __init__
  2. b.
    name
  3. c.
    pet_1

Answer

C. pet_1
pet_1 is an instance of the Cat class created by calling Cat(). The other instance is pet_2.

Concepts in Practice 11.2.3 §11.2 source ↗

Consider the example below:

class Cat:
  def __init__(self):
    self.name = 'Kitty'
    self.breed = 'domestic short hair'
    self.age = 1
  def print_info(self):
    print(self.name, 'is a ', self.age, 'yr old', self.breed)

pet_1 = Cat()
pet_2 = Cat()
Which of the following is an attribute?
  1. a.
    breed
  2. b.
    pet_2
  3. c.
    print_info

Answer

A. breed
breed is an instance attribute defined in __init__(). The other instance attributes are name and age.

Concepts in Practice 11.2.4 §11.2 source ↗

Consider the example below:

class Cat:
  def __init__(self):
    self.name = 'Kitty'
    self.breed = 'domestic short hair'
    self.age = 1
  def print_info(self):
    print(self.name, 'is a ', self.age, 'yr old', self.breed)

pet_1 = Cat()
pet_2 = Cat()
Suppose the programmer wanted to change the class to represent a pet cat. Which is the appropriate name that follows PEP 8 recommendations?
  1. a.
    petcat
  2. b.
    pet_cat
  3. c.
    PetCat

Answer

C. PetCat
CapWords style, with all words capitalized and no spaces between words, is recommended for class names. "Pet" and "cat" are separate words, so each is capitalized and one directly follows the other.

Concepts in Practice 11.2.5 §11.2 source ↗

Consider the example below:

 1  class Rectangle:
 2    def __init__(self):
 3      self.length = 1
 4      self.width = 1
 5    def area(self):
 6      return self.length * self.width
 7  
 8  room_1 = Rectangle()
 9  room_1.length = 10
10  room_1.width = 15
11  print("Room 1's area:", room_1.area())
12  room_3 = Rectangle()
13  room_3.length = 12
14  room_3.width = 14
15  print("Room 3's area:", room_3.area())
How many times is __init__() called?
  1. a.
    1
  2. b.
    2
  3. c.
    3

Answer

B. 2
Two instances, room_1 and room_3, are created by calling Rectangle(), which calls the constructor __init__().

Concepts in Practice 11.2.6 §11.2 source ↗

Consider the example below:

 1  class Rectangle:
 2    def __init__(self):
 3      self.length = 1
 4      self.width = 1
 5    def area(self):
 6      return self.length * self.width
 7  
 8  room_1 = Rectangle()
 9  room_1.length = 10
10  room_1.width = 15
11  print("Room 1's area:", room_1.area())
12  room_3 = Rectangle()
13  room_3.length = 12
14  room_3.width = 14
15  print("Room 3's area:", room_3.area())
When line 11 executes, execution flow moves to line 5. What does self represent on line 5?
  1. a.
    the area of room_1
  2. b.
    the instance room_1
  3. c.
    the Rectangle class

Answer

B. the instance room_1
room_1 is the instance that called the method area(), so self represents the specific instance.

Concepts in Practice 11.2.7 §11.2 source ↗

Consider the example below:

 1  class Rectangle:
 2    def __init__(self):
 3      self.length = 1
 4      self.width = 1
 5    def area(self):
 6      return self.length * self.width
 7  
 8  room_1 = Rectangle()
 9  room_1.length = 10
10  room_1.width = 15
11  print("Room 1's area:", room_1.area())
12  room_3 = Rectangle()
13  room_3.length = 12
14  room_3.width = 14
15  print("Room 3's area:", room_3.area())
Which line initializes the instance attribute length?
  1. a.
    3
  2. b.
    6
  3. c.
    9

Answer

A. 3
Line 3 is in __init__(), which initializes length and the other instance attributes for each new instance.

Concepts in Practice 11.2.8 §11.2 source ↗

Consider the example below:

 1  class Rectangle:
 2    def __init__(self):
 3      self.length = 1
 4      self.width = 1
 5    def area(self):
 6      return self.length * self.width
 7  
 8  room_1 = Rectangle()
 9  room_1.length = 10
10  room_1.width = 15
11  print("Room 1's area:", room_1.area())
12  room_3 = Rectangle()
13  room_3.length = 12
14  room_3.width = 14
15  print("Room 3's area:", room_3.area())
Suppose line 2 is changed to def __init__():. What would room_1's attributes be initialized to?
  1. a.
    length = 0, width = 0
  2. b.
    length = 1, width = 1
  3. c.
    Error

Answer

C. Error
__init__() has one required parameter, conventionally called self, which allows the constructor to access the instance.

Concepts in Practice 11.2.9 §11.2 source ↗

Consider the example above.

Which is an instance attribute?
  1. a.
    loc
  2. b.
    order_id
  3. c.
    order_3
Video · Using class attributes for shared coffee order information in the book ↗

Answer

B. order_id
order_id is an instance attribute defined in __init__(). The other instance attribute is cup_size.

Concepts in Practice 11.2.10 §11.2 source ↗

Consider the example above.

Suppose the line order_1.cup_size = 8 is added before order_3.print_order(). What is the new output?
  1. a.
    Cafe Coffee Order 3 : 8 oz
  2. b.
    Cafe Coffee Order 3 : 16 oz
  3. c.
    Error
Video · Using class attributes for shared coffee order information in the book ↗

Answer

B. Cafe Coffee Order 3 : 16 oz
Changing order_1.cup_size does not affect order_3.cup_size. order_1.cup_size changes to 8 and order_3.cup_size is still 16 .

Concepts in Practice 11.2.11 §11.2 source ↗

Consider the example above.

Suppose the line CoffeeOrder.loc = 'Caffeine Cafe' is added before order_3.print_order(). What is the new output?
  1. a.
    Caffeine Cafe Order 3 : 16 oz
  2. b.
    Cafe Coffee Order 3 : 16 oz
  3. c.
    Error
Video · Using class attributes for shared coffee order information in the book ↗

Answer

A. Caffeine Cafe Order 3 : 16 oz
order_1, order_2, and order_3 all share the class attribute CoffeeOrder.loc. Changing loc affects all instances, so Caffeine Cafe is printed as the location.

Concepts in Practice 11.2.12 §11.2 source ↗

Consider the example above.

Suppose the line self.cls_id = 5 is added to the end of __init__()'s definition. What is the new output?
  1. a.
    Cafe Coffee Order 5 : 16 oz
  2. b.
    Cafe Coffee Order 3 : 16 oz
  3. c.
    Error
Video · Using class attributes for shared coffee order information in the book ↗

Answer

B. Cafe Coffee Order 3 : 16 oz
Trying to access a class attribute using an instance is unsafe. In __init__(), trying to access the class attribute creates a new instance attribute called cls_id. Though possible, programmers should avoid using the same name for class attributes and instance attributes to avoid confusion.

Concepts in Practice 11.3.1 §11.3 source ↗

Consider the example above.

Suppose the programmer wanted to make blood pressure a required parameter in __init__(). Which is the correct __init__() method header?
  1. a.
    def __init__(p_id, bp, self, tmp=-1.0, hr=-1, rr=-1):
  2. b.
    def __init__(self, p_id, bp, tmp=-1.0, hr=-1, rr=-1):
  3. c.
    def __init__(self, p_id, bp=[-1,-1], tmp=-1.0, hr=-1, rr=-1):
Video · Creating patient vital signs instances in the book ↗

Answer

B. def __init__(self, p_id, bp, tmp=-1.0, hr=-1, rr=-1):
Removing the default parameter value makes bp a required parameter.

Concepts in Practice 11.3.2 §11.3 source ↗

Consider the example above.

Which is a correct call to __init__() to create an instance with p_id=5241?
  1. a.
    patient_10 = Vitals(self, 5241)
  2. b.
    patient_10 = Vitals(5241)
  3. c.
    both
Video · Creating patient vital signs instances in the book ↗

Answer

B. patient_10 = Vitals(5241)
self is the first parameter in __init__() definition, not an explicit argument. self should not be included in the call.

Concepts in Practice 11.3.3 §11.3 source ↗

Consider the example above.

Suppose another __init__() definition is added after the first with the header as follows:
def __init__(self, p_id, bp, tmp, hr, rr)
What is the impact on the program?
  1. a.
    no change.
  2. b.
    Second __init__() definition produces an error.
  3. c.
    First two __init__() calls produce an error.
Video · Creating patient vital signs instances in the book ↗

Answer

C. First two __init__() calls produce an error.
The second definition overwrites the first as multiple explicit definitions of __init__() aren't allowed. __init__() requires all parameters, so the first two __init__() calls for patient_1 and patient_2 are incorrect.

Concepts in Practice 11.3.4 §11.3 source ↗

Consider the example below:

class CoffeeOrder:
  loc = 'Cafe Coffee'
  cls_id = 1

  def __init__(self, size=16, milk=False, sugar=False):
    self.order_id = CoffeeOrder.cls_id
    self.cup_size = size
    self.with_milk = milk
    self.with_sugar = sugar
    CoffeeOrder.cls_id += 1

  def change(self, milk, sugar):
    self.with_milk = milk
    self.with_sugar = sugar

  def print_order(self):
    print(CoffeeOrder.loc,'Order', self.order_id, ':', self.cup_size, 'oz')
    if self.with_milk:
      print('\twith milk')
    if self.with_sugar:
      print('\twith sugar')

order_1 = CoffeeOrder(8)
order_2 = CoffeeOrder(8, True, False)
order_1.change(False, True)
What does order_1 represent at the end of the program?
  1. a.
    8 oz coffee
  2. b.
    8 oz coffee with milk
  3. c.
    8 oz coffee with sugar

Answer

C. 8 oz coffee with sugar
order_1 is originally a coffee without milk or sugar, but the call to change() adds sugar to the order by assigning order_1.with_sugar with True .

Concepts in Practice 11.3.5 §11.3 source ↗

Consider the example below:

class CoffeeOrder:
  loc = 'Cafe Coffee'
  cls_id = 1

  def __init__(self, size=16, milk=False, sugar=False):
    self.order_id = CoffeeOrder.cls_id
    self.cup_size = size
    self.with_milk = milk
    self.with_sugar = sugar
    CoffeeOrder.cls_id += 1

  def change(self, milk, sugar):
    self.with_milk = milk
    self.with_sugar = sugar

  def print_order(self):
    print(CoffeeOrder.loc,'Order', self.order_id, ':', self.cup_size, 'oz')
    if self.with_milk:
      print('\twith milk')
    if self.with_sugar:
      print('\twith sugar')

order_1 = CoffeeOrder(8)
order_2 = CoffeeOrder(8, True, False)
order_1.change(False, True)
Why is change() an instance method?
  1. a.
    can change attributes
  2. b.
    has multiple parameters
  3. c.
    can change an instance

Answer

C. can change an instance
An instance method's first parameter indicates the method can change an instance. change() allows a change in whether a coffee order has milk or sugar.

Concepts in Practice 11.3.6 §11.3 source ↗

Consider the example below:

class CoffeeOrder:
  loc = 'Cafe Coffee'
  cls_id = 1

  def __init__(self, size=16, milk=False, sugar=False):
    self.order_id = CoffeeOrder.cls_id
    self.cup_size = size
    self.with_milk = milk
    self.with_sugar = sugar
    CoffeeOrder.cls_id += 1

  def change(self, milk, sugar):
    self.with_milk = milk
    self.with_sugar = sugar

  def print_order(self):
    print(CoffeeOrder.loc,'Order', self.order_id, ':', self.cup_size, 'oz')
    if self.with_milk:
      print('\twith milk')
    if self.with_sugar:
      print('\twith sugar')

order_1 = CoffeeOrder(8)
order_2 = CoffeeOrder(8, True, False)
order_1.change(False, True)
Can print_order() be unindented?
  1. a.
    yes
  2. b.
    no

Answer

B. no
Unindenting print_order() would produce an error. An instance method must be defined in the class.

Concepts in Practice 11.4.1 §11.4 source ↗

Which of the following is a magic method?
  1. a.
    add()
  2. b.
    _add_()
  3. c.
    __add__()

Answer

C. __add__()
__add__() is a magic method, indicated by the double underscores at the start and end of the method name.

Concepts in Practice 11.4.2 §11.4 source ↗

Why are magic methods special?
  1. a.
    can't be called by the user
  2. b.
    perform internal actions
  3. c.
    have fixed definitions

Answer

B. perform internal actions
Magic methods are designed to be invoked internally to perform under-the-hood actions to simplify tasks for the user.

Concepts in Practice 11.4.3 §11.4 source ↗

Consider the example above, and identify the magic method(s) in the updated program.
  1. a.
    __init__()
  2. b.
    __str__()
  3. c.
    __init__(), __str__()
Video · Customizing __str__() in a user-defined class, Engineer in the book ↗

Answer

C. __init__(), __str__()
__init__() is defined by the programmer to initialize instance attributes. __str__() is defined by the programmer to customize an Engineer instance's string representation.

Concepts in Practice 11.4.4 §11.4 source ↗

A programmer explicitly defining the modulo operator for their user-defined class is ___________ the operator.
  1. a.
    overloading
  2. b.
    rewriting
  3. c.
    implementing

Answer

A. overloading
A programmer can overload an operator to customize the built-in operator's function.

Concepts in Practice 11.4.5 §11.4 source ↗

Given the code below, which argument maps to the parameter other in the call to Account.__add__()?
acct_a = Account("Ashe", 6492)
acct_b = Account("Bevins", 5210)

acct_ab = acct_a + acct_b
  1. a.
    acct_a
  2. b.
    acct_b
  3. c.
    acct_ab

Answer

B. acct_b
The addition operation maps the left operand, acct_a, to the parameter self and the right operand, acct_b, to the parameter other.

Concepts in Practice 11.4.6 §11.4 source ↗

Which __sub__() definition overloads the - operator for the code below to work?
class Pair:
  def __init__(self, x=0, y=0):
    self.x = x
    self.y = y
  # Define __sub__()

p1 = Pair(10, 2)
p2 = Pair(8, 4)
p3 = p1 - p2
print(p3.x, p3.y)
  1. a.
    def __sub__(self):
      return Pair(self.x - other.x, self.y - other.y)
  2. b.
    def __sub__(self, other):
      return self.x - other.x, self.y - other.y
  3. c.
    def __sub__(self, other):
      return Pair(self.x - other.x, self.y - other.y)

Answer

C.
def __sub__(self, other):
  return Pair(self.x - other.x, self.y - other.y)
- is a binary operator, so __sub__() has two parameters. The parameters' x and y attributes are subtracted from each other, and the resulting values are made into a new Pair.

Concepts in Practice 11.4.7 §11.4 source ↗

Consider the example above.

How many operators are overloaded?
  1. a.
    3
  2. b.
    4
  3. c.
    5

Answer

A. 3
<, >, and == are overloaded with __lt__(), __gt__(), and __eq__(), respectively.

Concepts in Practice 11.4.8 §11.4 source ↗

Consider the example above.

Which code appropriately overloads the <= operator?
  1. a.
    def __le__(other):
      return self.amount <= other.amount
  2. b.
    def __le__(self, other):
      return self.amount <= other.amount
  3. c.
    def __le__(self, other):
      return other.amount <= self.amount

Answer

B.
def __le__(self, other):
  return self.amount <= other.amount
__le__() is the magic method for the <= operator. __le__() takes two parameters for the left and right operand, and returns the correct comparison of the two amount values.

Concepts in Practice 11.4.9 §11.4 source ↗

Consider the example above.

Which type of value does __gt__() return?
  1. a.
    account instance
  2. b.
    Boolean
  3. c.
    integer

Answer

B. Boolean
__gt__() overloads the > operator, which makes a comparison and returns True or False .

Concepts in Practice 11.5.1 §11.5 source ↗

Consider the example above. How many classes are imported in the second main.py?
  1. a.
    1
  2. b.
    2
  3. c.
    3
Video · Importing classes from files in the book ↗

Answer

B. 2
Level and XP are classes imported from the character module into the program. Any other class in the character module is not imported.

Concepts in Practice 11.5.2 §11.5 source ↗

Which line imports only the Level class from character?
  1. a.
    import Level from character
  2. b.
    from character import Level
  3. c.
    import Level

Answer

B. from character import Level
A single class or multiple classes can be imported from a module using the class name(s).

Concepts in Practice 11.5.3 §11.5 source ↗

How many classes can be in a module?
  1. a.
    none
  2. b.
    only 1
  3. c.
    any number

Answer

C. any number
The number of classes in a module is unlimited, but classes should be grouped in modules to maximize reusability.

Concepts in Practice 11.5.4 §11.5 source ↗

Consider the example above. Suppose a program imports the character module using import character as game_char.

How would the program create a Level instance?
  1. a.
    rogue_level = character.Level()
  2. b.
    rogue_level = game_char.Level()
  3. c.
    rogue_level = character.game_char.Level()

Answer

B. rogue_level = game_char.Level()
The character module is aliased as game_char, so character is not defined in the program. game_char is used in place of character.

Concepts in Practice 11.5.5 §11.5 source ↗

Consider the example above. Suppose a program imports the character module using import character as game_char.

Which code creates a name collision?
  1. a.
    character = 'Ranger'
  2. b.
    Game_char = 'Ranger'
  3. c.
    game_char = 'Ranger'

Answer

C. game_char = 'Ranger'
game_char referred to the imported module, but assigning game_char replaces the imported module with the string 'Ranger' . game_char can no longer be used to access classes.

Loading chapter 12…

Problems and answers are adapted from Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield and Narges Norouzi, OpenStax, and are used under the CC BY-NC-SA 4.0 licence. Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction. Illustrations: Copyright Rice University, OpenStax, under CC BY-NC-SA 4.0 license. This adaptation is released under the same licence, is non-commercial, and is neither affiliated with nor endorsed by OpenStax or Rice University.