Question 91
Which pair of dunder methods must an object implement to satisfy the Iterator Protocol in Python?
An iterable implements __iter__(). An iterator implements both __iter__() (returning self) and __next__().
Which pair of dunder methods must an object implement to satisfy the Iterator Protocol in Python?
An iterable implements __iter__(). An iterator implements both __iter__() (returning self) and __next__().
Evaluate:
def double_dec(func):
def wrapper(x):
return func(x) * 2
return wrapper
def inc_dec(func):
def wrapper(x):
return func(x) + 1
return wrapper
@double_dec
@inc_dec
def calc(x):
return xprint(calc(5))
$Decorators apply bottom-up: calc = double_dec(inc_dec(calc)). calc(5) -> inc_dec gives 5+1=6 -> double_dec gives 6*2=12.$
What happens when calling raise without arguments inside an except block?
A bare raise inside an except block re-raises the active exception currently being processed.
What is the output?
def test():
try:
raise ValueError('err')
except ValueError:
return 1
except Exception:
return 2
else:
return 3print(test())
ValueError is caught by the specific except ValueError: block, returning 1.
Which built-in exception is the base class for all non-exit built-in exceptions in Python?
All non-system-exiting exceptions inherit from Exception. (BaseException is the root for SystemExit, KeyboardInterrupt, etc.).