Look at the code below. What will be printed after running it?
class Box: def __init__(self, length, width): self.length = length self.width = width def resize(self, new_length, new_width): self.length = new_length self.width = new_width box = Box(5, 3) box.resize(10, 6) print(box.length, box.width)
Think about what the resize method does to the object's attributes.
The resize method changes the length and width attributes of the box object to 10 and 6 respectively. So, printing them shows 10 6.
Consider this class that modifies its internal counter. What is the final value printed?
class Counter: def __init__(self): self.count = 0 def increment(self): self.count += 1 def reset(self): self.count = 0 c = Counter() c.increment() c.increment() c.reset() c.increment() print(c.count)
Follow the changes to count step by step.
The counter increments twice to 2, then resets to 0, then increments once more to 1. So the final value is 1.
What will this code print?
class Basket: def __init__(self): self.items = [] def add_item(self, item): self.items.append(item) b = Basket() b.add_item('apple') b.add_item('banana') print(b.items)
Think about how the list items changes when you append new elements.
The add_item method adds each item to the items list. After adding 'apple' and 'banana', the list contains both.
What happens when this code runs?
class Car: def __init__(self, model): self.model = model car = Car('Sedan') car.speed = 60 print(car.speed) print(car.color)
Check which attributes exist and which do not.
Assigning car.speed = 60 creates the attribute speed. Printing it shows 60. But car.color was never set, so accessing it raises AttributeError.
You want to keep track of all values assigned to an attribute value in an object. Which code correctly updates the history each time value changes?
Think about how to run code automatically when an attribute changes.
Option D uses a property setter to update _value and append to history every time value changes. This tracks all changes correctly.
Other options either don't use property setters or overwrite history incorrectly.