Question 56
What is the output of:
class Multiplier:
def __init__{self, factor}:
self.factor = factor
def __call__{self, val}:
return self.factor * val$m = Multiplier(3)
print(m(10))$
$m(10) invokes m.__call__{10}, returning 3 * 10 = 30.$
What is the output of:
class Multiplier:
def __init__{self, factor}:
self.factor = factor
def __call__{self, val}:
return self.factor * val$m = Multiplier(3)
print(m(10))$
$m(10) invokes m.__call__{10}, returning 3 * 10 = 30.$
What is the purpose of the @property decorator in Python?
@property allows a method to be accessed like an attribute (without parentheses ()), providing clean getter/setter syntax.
Evaluate the code:
class Circle:
def __init__{self, radius}:
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, val):
if val > 0:
self._radius = val$c = Circle(5)
c.radius = -10
c.radius = 8
print(c.radius)$
c.radius = -10 fails the val > 0 check so _radius stays 5. c.radius = 8 sets _radius to 8.
Which dunder method is invoked when evaluating x in obj?
The in membership operator invokes obj.__contains__(x).
What is printed by the following code?
class CustomList:
def __init__{self, data}:
self.data = data
def __getitem__{self, idx}:
return self.data[idx] * 2cl = CustomList([10, 20, 30])
print(cl[1])
$cl[1] calls cl.__getitem__{1}, returning self.data[1] * 2 = 20 * 2 = 40.$