Classes & Instances

Preview — 3 of 10 questions

What is the output of the following code?

javascript
class ShoppingCart:
    items = []

    def add(self, item):
        self.items.append(item)

cart1 = ShoppingCart()
cart2 = ShoppingCart()
cart1.add("apple")
cart2.add("banana")
print(cart1.items)
print(cart2.items)
A['apple'] then ['apple', 'banana']
B['apple'] then ['banana']
C['apple', 'banana'] then ['apple', 'banana']
D[] then ['banana']

What is the output of the following code?

javascript
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return f"{self.name} says woof"

d = Dog("Rex")
print(d.bark())
print(Dog.bark(d))
ARex says woof then Rex says woof
BRex says woof then TypeError
CRex says woof then AttributeError
DTypeError then Rex says woof

What is the output of the following code?

javascript
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @staticmethod
    def is_freezing(celsius):
        return celsius <= 0

    @classmethod
    def from_fahrenheit(cls, fahrenheit):
        return cls((fahrenheit - 32) * 5 / 9)

t = Temperature.from_fahrenheit(32)
print(round(t.celsius))
print(Temperature.is_freezing(-5))
ATypeError
B32 then True
C0 then False
D0 then True

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.