Consider a Button class that calls a callback function when pressed. What will be printed when the button is pressed?
class Button: def __init__(self, callback): self.callback = callback def press(self): self.callback() def greet(): print("Button pressed!") btn = Button(greet) btn.press()
Think about what the press method does with the callback.
The press method calls the callback function greet, which prints "Button pressed!" once.
In a Button class that accepts a callback function, which of the following is true about how callbacks work?
Think about when the callback is executed.
The callback is saved during initialization and only called when the button is pressed, not before.
What error does the following code raise when btn.press() is called?
class Button: def __init__(self, callback): self.callback = callback def press(self): self.callback(self) def greet(): print("Hello") btn = Button(greet) btn.press()
Check how the callback is called and how it is defined.
The press method calls self.callback(self), passing one argument, but greet expects none, causing a TypeError.
Choose the correct Button class definition where the callback function accepts the Button instance as an argument.
The callback should be called with exactly one argument: the Button instance.
Option B correctly calls the callback with self once. Others either call with no arguments or wrong arguments.
Given the code below, what is printed when btn.press() is called?
class Button: def __init__(self): self.callbacks = [] def add_callback(self, cb): self.callbacks.append(cb) def press(self): for cb in self.callbacks: cb(self) def cb1(btn): print("First callback") def cb2(btn): print("Second callback") btn = Button() btn.add_callback(cb1) btn.add_callback(cb2) btn.press()
Callbacks are called in the order they were added.
The press method calls each callback in the list in order, so cb1 prints first, then cb2.