This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Classes and Objects, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
Which method initialises a new object?
Answer: __init__
Why: __init__ runs automatically when an instance is created.
What does self refer to inside a method?
Answer: The current instance
Why: self is the object on which the method was called.
How do you create an instance of Order?
Answer: Order("latte", 4.5)
Why: Call the class like a function to create an instance.
What is an attribute?
Answer: Data stored on an object
Why: Attributes hold the state of a particular object.
Complete the method name that initialises the object.
class Order:
def ____(self, drink):
self.drink = drinkAnswer: __init__
Why: __init__ is the initialiser method.
Complete the attribute assignment for the drink parameter.
class Order:
def __init__(self, drink):
self.____ = drinkAnswer: drink
Why: self.drink stores the parameter on the instance.
Complete the expression that multiplies price by quantity.
class Order:
def total(self):
return self.price ____ self.quantityAnswer: *
Why: self.price * self.quantity uses the object's own attributes.
Complete the call that creates an Order instance.
order = ____("latte", 4.5)
print(order.price)Answer: Order
Why: The class name followed by parentheses creates an instance.
What is printed?
class A:
def __init__(self, x):
self.x = x
print(A(3).x)Answer: 3
Why: The instance stores 3 in its x attribute.
What is the output?
class A:
def value(self):
return 7
print(A().value())Answer: 7
Why: The method returns 7.
What does this code print?
class Order:
def __init__(self, price, quantity=2):
self.price = price
self.quantity = quantity
print(Order(4).price * Order(4).quantity)Answer: 8
Why: Each Order gets price 4 and quantity 2, so the product is 8.
What does the program output?
class A:
pass
print(A().__class__.__name__)Answer: A
Why: The class name is A.
Try the questions first
Open the practice page for Python Classes and Objects and answer the same 12 questions with instant feedback.