Lec 18 Protocols
Interfaces using abstract classes are enforced
- Early error catching
Contracts are followed by convention, but not enforced
- Specifies what methods should do, rather than list the methods to be implemented
Len protocol:
__len__()can be overridden, to replacelen(obj)- Can implement Sized interface, to force sizing
from collections.abc import Sizedclass ClassName(Sized)-> must implement__len__()
Membership test protocol
incalls__contains__()from collections.abc import Containerclass Document(Container[str])-> must implement__contains__
Iterable protocol
for, incalls__iter__(self) -> Iterator[str]method__next__(self) -> T: returns the next value in the sequence, or raisesStopIterationif there are no more values left to iterate through
class AlternatingDayIterator(Iterator[str]):
def init(self, days: list[str]) -> None:
self.index = 0<span class="token keyword">def</span> <span class="token function">__next__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> <span class="token builtin">str</span><span class="token punctuation">:</span> <span class="token comment">#if there are no days left, raise StopIteration</span> <span class="token keyword">if</span> self<span class="token punctuation">.</span>index <span class="token operator">>=</span> <span class="token builtin">len</span><span class="token punctuation">(</span>self<span class="token punctuation">.</span>days<span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">raise</span> StopIteration <span class="token comment"># if there are days left:</span> <span class="token comment"># figure out which day to return next</span> <span class="token comment"># increment index</span> <span class="token comment"># return the day</span> day_to_ret <span class="token operator">=</span> self<span class="token punctuation">.</span>days<span class="token punctuation">[</span>self<span class="token punctuation">.</span>index<span class="token punctuation">]</span> self<span class="token punctuation">.</span>index <span class="token operator">+=</span> <span class="token number">2</span> <span class="token keyword">return</span> day_to_ret</div>
class Interable(Iterable[int]):
def __init__(self, number: int) -> None:
self.number = number
def __iter__(self) -> Iterator[int]:
return Digiterator(self.number)
class Digiterator(Iterator[int]):
def __init__(self, number: int) -> None:
self.number = number
def __next__(self) -> int:
digit = self.num % 10 # rightmost
rest = self.number // 10 # integer division (truncates)
return digit
for digit in INTerable(34567):
print(f"{34567}")