certain-design-patterns/iterator.py

28 lines
890 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from typing import List, Iterator
# юзер = его имя + список друзей
class VkUser:
def __init__(self, name: str, friends: List[str]):
self.name = name
self.friends = friends
def get_friends(self) -> List[str]:
return self.friends
class VkFriendIterator(Iterator):
def __init__(self, vk_user: VkUser):
self._vk_user = vk_user
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index < len(self._vk_user.get_friends()):
friend = self._vk_user.get_friends()[self._index]
self._index += 1
return friend
else:
raise StopIteration
user = VkUser("Alice", ["Bob", "Charlie", "David", "Emma"])
friends_iterator = VkFriendIterator(user)
print(f"Friends of {user.name}:")
for friend in friends_iterator:
print(friend)