Skip to content

Instantly share code, notes, and snippets.

@artemonsh
Created October 28, 2025 08:56
Show Gist options
  • Select an option

  • Save artemonsh/fb9b655e5c5a0e9cce68f211f9c6c365 to your computer and use it in GitHub Desktop.

Select an option

Save artemonsh/fb9b655e5c5a0e9cce68f211f9c6c365 to your computer and use it in GitHub Desktop.
# ПРИМЕР 1
from collections.abc import Iterator
class PrintingIterator(Iterator):
def __init__(self, items):
self.items = items
self.index = 0
print("Inited printing iterator with items", items)
def __next__(self):
if self.index >= len(self.items):
print("Index out of range, stopping iteration")
raise StopIteration
value = self.items[self.index]
self.index += 1
print("* returning value", value, "from index", self.index)
return value
# ПРИМЕР 2
class NetworkConnection:
def __init__(self, url):
self.url = url
self._conn = None
def __enter__(self):
self._conn = object()
print(f"Connecting to {self.url!r}, conn: {self._conn!r}")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
print(f"got an exception {exc_type}, closing connection")
print(f"Closing connection to {self.url!r}, conn: {self._conn!r}")
# ПРИМЕР 3
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self, other):
return self.__class__(
self.x + other.x,
self.y + other.y,
)
# ПРИМЕР 4
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment