diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/.DS_Store differ diff --git a/hw-05/task5.py b/hw-05/task5.py new file mode 100644 index 0000000..4cc91a0 --- /dev/null +++ b/hw-05/task5.py @@ -0,0 +1,87 @@ +class Node: + """Элемент списка List2L""" + def __init__(self, key=None, value=None): + """Инициализация""" + self.key = key + self.value = value + self.prev = None + self.next = None + + def get_key(self): + """Получить ключ""" + return self.key + + def get_value(self): + """Получить значение""" + return self.value + + def set_value(self, val): + """Установить значение""" + self.value = val + + +class List2L: + """Классический двусвязный список""" + def __init__(self): + """Инициализация""" + self.head = Node() + self.tail = Node() + self.head.next = self.tail + self.tail.prev = self.head + + def add_front(self, node): + """Добавляем ноду в начало""" + node.prev = self.head + node.next = self.head.next + + self.head.next.prev = node + self.head.next = node + + def remove(self, node): + """Удаляем ноду из любой позиции""" + prev_node = node.prev + next_node = node.next + + prev_node.next = next_node + next_node.prev = prev_node + + def pop_last(self): + """Достаём последний элемент списка""" + last_node = self.tail.prev + self.remove(last_node) + return last_node + + +class LRUCache: + """Класс для кеширования объектов""" + def __init__(self, limit=42): + """Инициализация""" + self.limit = limit + self.list = List2L() + self.cache = {} + + def get(self, key): + """Получить значение""" + if key not in self.cache: + return None + + node = self.cache[key] + self.list.remove(node) + self.list.add_front(node) + return node.get_value() + + def set(self, key, value): + """Установить значение""" + if key in self.cache: + node = self.cache[key] + node.set_value(value) + self.list.remove(node) + self.list.add_front(node) + else: + if len(self.cache) >= self.limit: + last_node = self.list.pop_last() + self.cache.pop(last_node.get_key()) + + new_node = Node(key, value) + self.cache[key] = new_node + self.list.add_front(new_node) diff --git a/hw-05/test_task5.py b/hw-05/test_task5.py new file mode 100644 index 0000000..aa022c0 --- /dev/null +++ b/hw-05/test_task5.py @@ -0,0 +1,18 @@ +from task5 import LRUCache + + +def test_predict_general_cases(): + cache = LRUCache(2) + + cache.set("k1", "val1") + cache.set("k2", "val2") + + assert cache.get("k3") is None + assert cache.get("k2") == "val2" + assert cache.get("k1") == "val1" + + cache.set("k3", "val3") + + assert cache.get("k3") == "val3" + assert cache.get("k2") is None + assert cache.get("k1") == "val1" diff --git a/hw-07/fetcher.py b/hw-07/fetcher.py new file mode 100644 index 0000000..1217674 --- /dev/null +++ b/hw-07/fetcher.py @@ -0,0 +1,81 @@ +"""Async URL fetcher: для асинхронной обкачки урлов""" + +import argparse +import ssl +import asyncio +import aiohttp + + +async def fetch_url(url, session, sem): + """ + Асинхронно скачивает старницу + Через semaphor контролирует кол-во одновременных запросов + """ + async with sem: + try: + ssl_context = ssl.create_default_context() + ssl_context.check_hostname = False + ssl_context.verify_mode = ssl.CERT_NONE + async with session.get(url, ssl=ssl_context) as resp: + text = await resp.text() + print(f"Fetched {url}") + return text + except (asyncio.TimeoutError, + aiohttp.client_exceptions.ClientConnectorDNSError) as e: + print(f"Error fetching {url}: {e}") + return None + + +async def fetch_batch_urls(urls, session, sem): + """ + Асинхронно запускает все задачи на обкачку урлов + вывод + """ + tasks = [ + asyncio.create_task(fetch_url(url, session, sem)) + for url in urls + ] + result = await asyncio.gather(*tasks) + for i, text in enumerate(result): + if text is not None: + print(f"Result {i}: {text[:100]}") + + +def read_urls_from_file(filename): + """ + Считывает урлы из файла + """ + with open(filename, "r", encoding="utf-8") as f: + return [line.strip() for line in f if line.strip()] + + +def parse_args(): + """ + Собирает аргументы командной строки + """ + parser = argparse.ArgumentParser() + parser.add_argument("concurrency", type=int) + parser.add_argument("urlfile", type=str) + return parser.parse_args() + + +async def run(urls, concurrency): + """ + Создаёт объекты семафор и aiohttp, запускает обкачку urlов + """ + sem = asyncio.Semaphore(concurrency) + async with aiohttp.ClientSession() as session: + await fetch_batch_urls(urls, session, sem) + + +def main(): + """ + Точка входа. Собираем аргументы командной строки, считываем данные + И запускаем асинхронное выполнение задач + """ + args = parse_args() + urls = read_urls_from_file(args.urlfile) + asyncio.run(run(urls, args.concurrency)) + + +if __name__ == "__main__": + main() diff --git a/hw-07/test_task7.py b/hw-07/test_task7.py new file mode 100644 index 0000000..b70d5d1 --- /dev/null +++ b/hw-07/test_task7.py @@ -0,0 +1,63 @@ +""" Файл для тестирования """ + + +import asyncio +import sys +import aiohttp +import pytest + + +from fetcher import read_urls_from_file, parse_args, run +from fetcher import fetch_url + + +@pytest.mark.asyncio +async def test_fetch_url_success(): + """Сценарий успешного фетчинга""" + sem = asyncio.Semaphore(1) + with open('urls.txt', encoding='utf-8') as f: + url = f.read().split('\n')[-1] + async with aiohttp.ClientSession() as session: + + text = await fetch_url(url, session, sem) + assert text is not None + assert 'decoreo.ru' in text + + +@pytest.mark.asyncio +async def test_fetch_url_fail(): + """Сценарий не успешного фетчинга""" + sem = asyncio.Semaphore(1) + async with aiohttp.ClientSession() as session: + url = "https://some-weird-link/" + text = await fetch_url(url, session, sem) + assert text is None + + +def test_read_urls_from_file(): + """Тестирует функцию чтения урлов из файла""" + with open('urls.txt', encoding='utf-8') as f: + old_urls = f.read().split('\n') + with open('test_urls.txt', 'w', encoding='utf-8') as f: + f.write('\n'.join(old_urls)) + urls = read_urls_from_file(f.name) + assert urls == old_urls + + +def test_parse_args(monkeypatch): + """Тестирует парсинг аргументов командной строки""" + test_args = ["fetcher.py", "5", "urls.txt"] + monkeypatch.setattr(sys, "argv", test_args) + args = parse_args() + assert args.concurrency == 5 + assert args.urlfile == "urls.txt" + + +@pytest.mark.asyncio +async def test_run(tmp_path): + """Тестирует функцию run.""" + file = tmp_path / "urls.txt" + lurl = "https://geotargetly.com/" + file.write_text(lurl) + urls = read_urls_from_file(str(file)) + await run(urls, 1) diff --git a/hw-07/test_urls.txt b/hw-07/test_urls.txt new file mode 100644 index 0000000..3eb938d --- /dev/null +++ b/hw-07/test_urls.txt @@ -0,0 +1,6 @@ +https://ru.wikipedia.org/wiki/Заглавная_страница +https://ru.wikipedia.org/wiki/Заглавная_страница +https://ru.wikipedia.org/wiki/Заглавная_страница +https://decoreo.ru/product-category/mebel/shkafy-kupe/?srsltid=AfmBOoo9YSOL-iXEHJx2hjSo3W5KMWCl9L20OBtFUvS3nCDgAe3dBR5B +https://decoreo.ru/product-category/mebel/shkafy-kupe/?srsltid=AfmBOoo9YSOL-iXEHJx2hjSo3W5KMWCl9L20OBtFUvS3nCDgAe3dBR5B +https://decoreo.ru/product-category/mebel/shkafy-kupe/?srsltid=AfmBOoo9YSOL-iXEHJx2hjSo3W5KMWCl9L20OBtFUvS3nCDgAe3dBR5B \ No newline at end of file diff --git a/hw-07/urls.txt b/hw-07/urls.txt new file mode 100644 index 0000000..3eb938d --- /dev/null +++ b/hw-07/urls.txt @@ -0,0 +1,6 @@ +https://ru.wikipedia.org/wiki/Заглавная_страница +https://ru.wikipedia.org/wiki/Заглавная_страница +https://ru.wikipedia.org/wiki/Заглавная_страница +https://decoreo.ru/product-category/mebel/shkafy-kupe/?srsltid=AfmBOoo9YSOL-iXEHJx2hjSo3W5KMWCl9L20OBtFUvS3nCDgAe3dBR5B +https://decoreo.ru/product-category/mebel/shkafy-kupe/?srsltid=AfmBOoo9YSOL-iXEHJx2hjSo3W5KMWCl9L20OBtFUvS3nCDgAe3dBR5B +https://decoreo.ru/product-category/mebel/shkafy-kupe/?srsltid=AfmBOoo9YSOL-iXEHJx2hjSo3W5KMWCl9L20OBtFUvS3nCDgAe3dBR5B \ No newline at end of file diff --git a/lesson-01/homework.md b/lesson-01/homework.md deleted file mode 100644 index 78128e8..0000000 --- a/lesson-01/homework.md +++ /dev/null @@ -1,55 +0,0 @@ -# Домашнее задание #01 (введение, тестирование) - -### 1. Функция оценки сообщения -Реализовать функцию `predict_message_mood`, которая принимает на вход строку `message` и пороги хорошести. -Функция возвращает: -- "неуд", если предсказание модели меньше `bad_threshold`; -- "отл", если предсказание модели больше `good_threshold`; -- "норм" в остальных случаях. - -Функция `predict_message_mood` создает экземпляр класса `SomeModel` и вызывает у этого экземпляра метод `predict` с аргументом `message`. - -```py -class SomeModel: - def predict(self, message: str) -> float: - # реализация не важна - - -def predict_message_mood( - message: str, - bad_thresholds: float = 0.3, - good_thresholds: float = 0.8, -) -> str: - ... - model.predict() - ... - - -assert predict_message_mood("Чапаев и пустота") == "отл" -assert predict_message_mood("Чапаев и пустота", 0.8, 0.99) == "норм" -assert predict_message_mood("Вулкан") == "неуд" -``` - -### 2. Генератор для чтения и фильтрации файла -Есть текстовый файл, который может не помещаться в память. -В каждой строке файла фраза или предложение: набор слов, разделенных пробелами (знаков препинания нет). - -Генератор должен принимать на вход: -- имя файла или файловый объект; -- список слов для поиска; -- список стоп-слов. - -Генератор перебирает строки файла и возвращает только те из них (строку целиком), где встретилось хотя бы одно из слов для поиска. -Если в одной строке сразу несколько совпадений, то вернуть строку надо лишь один раз. -Если в строке встретилось слово из списка стоп-слов, то такая строка должна игнорирроваться, даже если там есть совпадения по словам поиска. -Поиск совпадений и стоп-слов должен выполняться по полному совпадению слова без учета регистра. - -Например, для строки из файла "а Роза упала на лапу Азора" слово поиска "роза" должно найтись, а "роз" или "розан" - уже нет. -В случае той же строки "а Роза упала на лапу Азора", слова-совпадения "роза" и стоп-слова "азора" исходная строка должна будет быть отброщена. - -### 3. Тесты в отдельном модуле для каждого пункта - -### 4. Зеленый пайплайн в репе -Обязательно: тесты, покрытие, flake8, pylint. -Опционально можно добавить другие инструменты, например, mypy и black. -Покрытие тестов должно составлять не менее 90%. diff --git a/lesson-01/lesson-01.pdf b/lesson-01/lesson-01.pdf deleted file mode 100644 index d56b657..0000000 Binary files a/lesson-01/lesson-01.pdf and /dev/null differ diff --git a/lesson-01/test_user.py b/lesson-01/test_user.py deleted file mode 100644 index 698f0fc..0000000 --- a/lesson-01/test_user.py +++ /dev/null @@ -1,179 +0,0 @@ -import unittest -from unittest import mock - -from user import User - - -class TestUser(unittest.TestCase): - - def test_init(self): - user = User("login", 42) - - self.assertEqual("login", user.name) - self.assertEqual(42, user.age) - - def test_greetings(self): - user = User("login", 42) - - self.assertEqual("login", user.name) - self.assertEqual("Hello, login!", user.greetings()) - - def test_birthday(self): - user = User("login", 42) - - self.assertEqual(42, user.age) - self.assertEqual(43, user.birthday()) - - self.assertEqual(43, user.age) - - def test_get_friends_not_work(self): - user = User("login", 42) - - with self.assertRaises(NotImplementedError): - user.get_friends() - - def test_get_friends_empty(self): - user = User("login", 42) - - with mock.patch("user.fetch_vk_api") as mock_fetch: - mock_fetch.return_value = [] - - self.assertEqual([], user.get_friends()) - self.assertEqual( - [mock.call("/friends", "login", part=None)], - mock_fetch.mock_calls, - ) - - self.assertEqual([], user.get_friends("some")) - self.assertEqual( - [ - mock.call("/friends", "login", part=None), - mock.call("/friends", "login", part="SOME"), - ], - mock_fetch.mock_calls, - ) - - def test_get_friends_single(self): - user = User("login", 42) - - with mock.patch("user.fetch_vk_api") as mock_fetch: - mock_fetch.return_value = ["password"] - - self.assertEqual(["password"], user.get_friends()) - self.assertEqual( - [mock.call("/friends", "login", part=None)], - mock_fetch.mock_calls, - ) - - self.assertEqual([], user.get_friends("some")) - self.assertEqual( - [ - mock.call("/friends", "login", part=None), - mock.call("/friends", "login", part="SOME"), - ], - mock_fetch.mock_calls, - ) - - self.assertEqual(["password"], user.get_friends("pass")) - self.assertEqual( - [ - mock.call("/friends", "login", part=None), - mock.call("/friends", "login", part="SOME"), - mock.call("/friends", "login", part="PASS"), - ], - mock_fetch.mock_calls, - ) - - def test_get_friends_many(self): - user = User("login", 42) - - with mock.patch("user.fetch_vk_api") as mock_fetch: - mock_fetch.side_effect = [ - ["password", "qwerty"], - ["password", "asdf"], - ["qwerty", "asdf"], - ] - - self.assertEqual(["password", "qwerty"], user.get_friends()) - self.assertEqual( - [mock.call("/friends", "login", part=None)], - mock_fetch.mock_calls, - ) - - self.assertEqual(["password", "asdf"], user.get_friends("a")) - self.assertEqual( - [ - mock.call("/friends", "login", part=None), - mock.call("/friends", "login", part="A"), - ], - mock_fetch.mock_calls, - ) - - self.assertEqual(["qwerty", "asdf"], user.get_friends()) - self.assertEqual( - [ - mock.call("/friends", "login", part=None), - mock.call("/friends", "login", part="A"), - mock.call("/friends", "login", part=None), - ], - mock_fetch.mock_calls, - ) - - @mock.patch("user.fetch_vk_api") - def test_get_friends_with_error(self, mock_fetch): - user = User("login", 42) - - mock_fetch.return_value = ["password"] - - self.assertEqual(["password"], user.get_friends()) - self.assertEqual( - [mock.call("/friends", "login", part=None)], - mock_fetch.mock_calls, - ) - - mock_fetch.side_effect = Exception("wrong") - - with self.assertRaises(Exception) as err: - user.get_friends("some") - - self.assertEqual("wrong", str(err.exception)) - self.assertEqual( - [ - mock.call("/friends", "login", part=None), - mock.call("/friends", "login", part="SOME"), - ], - mock_fetch.mock_calls, - ) - - @mock.patch("user.fetch_vk_api") - def test_get_friends_with_lambda(self, mock_fetch): - user = User("login", 42) - - mock_fetch.side_effect = lambda *a, **k: ["password"] - - self.assertEqual(["password"], user.get_friends()) - self.assertEqual( - [ - mock.call("/friends", "login", part=None), - ], - mock_fetch.mock_calls, - ) - - self.assertEqual(["password"], user.get_friends("pass")) - self.assertEqual( - [ - mock.call("/friends", "login", part=None), - mock.call("/friends", "login", part="PASS"), - ], - mock_fetch.mock_calls, - ) - - self.assertEqual([], user.get_friends("err")) - self.assertEqual( - [ - mock.call("/friends", "login", part=None), - mock.call("/friends", "login", part="PASS"), - mock.call("/friends", "login", part="ERR"), - ], - mock_fetch.mock_calls, - ) diff --git a/lesson-01/user.py b/lesson-01/user.py deleted file mode 100644 index 23dae2b..0000000 --- a/lesson-01/user.py +++ /dev/null @@ -1,30 +0,0 @@ -from vk_api import fetch_vk_api - - -class User: - def __init__(self, name, age): - self.name = name - self.age = age - - def greetings(self): - return f"Hello, {self.name}!" - - def birthday(self): - self.age += 1 - return self.age - - def get_friends(self, name_part=None): - if name_part: - name_part = name_part.upper() - - friends = fetch_vk_api( - "/friends", self.name, part=name_part - ) - - if name_part is not None: - name_part = name_part.lower() - friends = [ - fr for fr in friends if name_part in fr - ] - - return friends diff --git a/lesson-01/vk_api.py b/lesson-01/vk_api.py deleted file mode 100644 index 977c2bc..0000000 --- a/lesson-01/vk_api.py +++ /dev/null @@ -1,3 +0,0 @@ -def fetch_vk_api(path, username, part): - # requests.get(path, ...) - raise NotImplementedError diff --git a/lesson-02/board.py b/lesson-02/board.py deleted file mode 100644 index d3ff555..0000000 --- a/lesson-02/board.py +++ /dev/null @@ -1,66 +0,0 @@ -import time - -def timeit(inner): - def timer(*args, **kwargs): - start = time.time() - try: - res = inner(*args, **kwargs) - finally: - finish = time.time() - print(f"Measure: {finish - start}!") - return res - return timer - - -@timeit -def summator(a, b): - time.sleep(1) - return a + b - -def summutor_1(a, b): - time.sleep(1) - return a + b -summator_1 = timeit(summutor_1) - - -print(summator(1, 10)) - - -def meancall(k): - lst = [] - def timeit(inner): - def timer(*args, **kwargs): - start = time.time() - try: - res = inner(*args, **kwargs) - finally: - finish = time.time() - lst.append(finish - start) - mid = sum(lst[-k:]) / len(lst[-k:]) - print(f"Mean time ({k} times): {mid}") - return res - return timer - return timeit - - - -@meancall(k=5) -def summator(a, b): - time.sleep(1) - return a + b - -summator(1, 2) -summator(1, 2) -summator(1, 2) -summator(1, 2) -summator(1, 2) -summator(1, 2) - - -def add_1(a, b): - time.sleep(1) - return a + b -add_1 = meancall(k=2)(add_1) - - - diff --git a/lesson-02/class_02.ipynb b/lesson-02/class_02.ipynb deleted file mode 100644 index 000a296..0000000 --- a/lesson-02/class_02.ipynb +++ /dev/null @@ -1,1758 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "id": "83afb326-bfc9-4200-82e3-1714ef00a8d9", - "metadata": {}, - "outputs": [], - "source": [ - "d = {}" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "6b46a1e6-7327-4502-a315-ef5da5cf096c", - "metadata": {}, - "outputs": [], - "source": [ - "d[\"str\"] = 123" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "6aeb8b18-7bc9-4fc1-a7ca-09002713472a", - "metadata": {}, - "outputs": [], - "source": [ - "class Data:\n", - " def __hash__(self):\n", - " #print(\"hash\")\n", - " return super().__hash__()\n", - "\n", - " def __eq__(self, other):\n", - " print(\"eq\")\n", - " return super().__eq__(other)" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "2d64dbb0-9c51-45e4-8425-60dec6d43a0d", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "hash\n" - ] - } - ], - "source": [ - "x = Data()\n", - "d[x] = 42" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "9cfdb3a3-ac35-46f3-83e7-597e9d6bcf7a", - "metadata": {}, - "outputs": [], - "source": [ - "for i in range(100):\n", - " x = Data()\n", - " d[x] = i" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "9a264cbe-dd2c-4a64-a9eb-6b1a5a1e2349", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "<__main__.Data at 0x108642ad0>" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "78c8f71f-9afa-4eda-9745-d2dcc0e3fab7", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "eq\n" - ] - }, - { - "data": { - "text/plain": [ - "False" - ] - }, - "execution_count": 12, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x == 10" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d4d297f6-98e2-476d-8fd0-4dcdd4caccde", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "07065a37-9a4f-4b10-8d89-6a9d1add2bc4", - "metadata": {}, - "outputs": [], - "source": [ - "def fn2(x, *args):\n", - " print(x, args)\n", - "\n", - "\n", - "def fn3(x, **kwargs):\n", - " print(x, kwargs)\n", - "\n", - "\n", - "def fn4(*args, **kwargs):\n", - " return args, kwargs" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "57bc6d60-728a-4722-bed6-b43d34da5d08", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "10 ()\n", - "10 (20, 30, 40)\n" - ] - }, - { - "data": { - "text/plain": [ - "(None, None)" - ] - }, - "execution_count": 20, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "fn2(10), fn2(10, 20, 30, 40)" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "ead2f896-8575-48aa-bc3c-6da853e5771f", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "10 {'a': 20, 'b': 30}\n", - "10 {'a': 20, 'b': 30}\n", - "30 {'b': 10, 'a': 20}\n" - ] - }, - { - "data": { - "text/plain": [ - "(None, None, None)" - ] - }, - "execution_count": 25, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "fn3(10, a=20, b=30), fn3(x=10, a=20, b=30), fn3(b=10, a=20, x=30)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4229e622-84f4-40c8-b125-7fe9adb05543", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8bd7dcd5-51e8-43f5-8559-7e3d115cd2b8", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 38, - "id": "cec01c61-a55d-4166-8d6e-52af3d7d13a8", - "metadata": {}, - "outputs": [], - "source": [ - "def fn7(pos1, /, pos2, pos3=3, *args, kw1=11, **kwargs):\n", - " print(f\"{pos1=}, {pos2=}, {pos3=}, {args=}, {kw1=}, {kwargs=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "53eeb58e-5d5a-472f-bf7c-f5fc40c9f7a0", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "pos1=10, pos2=20, pos3=3, kw1=11, kwargs={}\n" - ] - } - ], - "source": [ - "fn7(10, 20)" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "ec1c1d71-f1e9-45a2-b00b-23e2e22d675e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "pos1=10, pos2=20, pos3=3, kw1=11, kwargs={}\n" - ] - } - ], - "source": [ - "fn7(10, pos2=20)" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "18b64f3e-a9ed-4415-9661-9a5b8088c28b", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "fn7() missing 1 required positional argument: 'pos1'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[34]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mfn7\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpos1\u001b[49m\u001b[43m=\u001b[49m\u001b[32;43m10\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mpos2\u001b[49m\u001b[43m=\u001b[49m\u001b[32;43m20\u001b[39;49m\u001b[43m)\u001b[49m\n", - "\u001b[31mTypeError\u001b[39m: fn7() missing 1 required positional argument: 'pos1'" - ] - } - ], - "source": [ - "fn7(pos1=10, pos2=20)" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "3c15be39-7c47-49c0-8b54-636cb356daab", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "pos1=10, pos2=20, pos3=30, kw1=11, kwargs={}\n" - ] - } - ], - "source": [ - "fn7(10, 20, 30)" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "3d669b1c-bb83-4a78-a017-cf0fce4acc4f", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "fn7() takes from 2 to 3 positional arguments but 4 were given", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[36]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mfn7\u001b[49m\u001b[43m(\u001b[49m\u001b[32;43m10\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m20\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m30\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m40\u001b[39;49m\u001b[43m)\u001b[49m\n", - "\u001b[31mTypeError\u001b[39m: fn7() takes from 2 to 3 positional arguments but 4 were given" - ] - } - ], - "source": [ - "fn7(10, 20, 30, 40)" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "cad0cd5f-853a-4a7a-a62e-319d84bf0a59", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "pos1=10, pos2=20, pos3=30, kw1=40, kwargs={'qwerty': 123}\n" - ] - } - ], - "source": [ - "fn7(10, 20, 30, kw1=40, qwerty=123)" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "4960b232-f285-4018-b76a-21d35fe8ac39", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "pos1=10, pos2=20, pos3=30, args=(40,), kw1=11, kwargs={}\n" - ] - } - ], - "source": [ - "fn7(10, 20, 30, 40)" - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "id": "5cee172a-1137-4068-8751-5919fcbdc2dc", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "pos1=10, pos2=20, pos3=30, args=(33,), kw1=40, kwargs={'qwerty': 123}\n" - ] - } - ], - "source": [ - "fn7(10, 20, 30, 33, kw1=40, qwerty=123)" - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "id": "72504036-8053-4143-a456-42e425f97600", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "pos1=10, pos2=20, pos3=30, args=(33,), kw1=40, kwargs={'kwargs': {'inner': 123}}\n" - ] - } - ], - "source": [ - "fn7(10, 20, 30, 33, kw1=40, kwargs={\"inner\": 123})" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4bd4a0ca-5dfe-4169-bfe9-be57b1d7b0cd", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 42, - "id": "680b119f-b3c5-4ec1-8ed5-87228d2c97f1", - "metadata": {}, - "outputs": [], - "source": [ - "def fn3(**kwargs):\n", - " print(kwargs)\n", - "\n", - "\n", - "def fn4(*args, **kwargs):\n", - " return fn3(**kwargs)" - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "id": "1222cd9f-ac72-4005-be63-b8bafc8aeaa7", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'x': 11, 'y': 22}\n" - ] - } - ], - "source": [ - "fn4(1, 2, x=11, y=22)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "234e2306-6cc4-4727-8e68-401e655a6dfa", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f9ba0b76-f92c-4ae3-bd9d-85ab01c405ea", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 45, - "id": "0d24e4b8-2855-4eef-a7be-d665b14090fc", - "metadata": {}, - "outputs": [], - "source": [ - "def double_param(x, **kwargs):\n", - " return x, kwargs" - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "id": "48e71d24-2985-41cc-98d0-6e269951a6ce", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "double_param() got multiple values for argument 'x'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[46]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mdouble_param\u001b[49m\u001b[43m(\u001b[49m\u001b[32;43m10\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mx\u001b[49m\u001b[43m=\u001b[49m\u001b[32;43m20\u001b[39;49m\u001b[43m)\u001b[49m\n", - "\u001b[31mTypeError\u001b[39m: double_param() got multiple values for argument 'x'" - ] - } - ], - "source": [ - "double_param(10, x=20)" - ] - }, - { - "cell_type": "code", - "execution_count": 47, - "id": "f50bac82-8bfe-40df-ab8c-33370f281740", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "double_param() got multiple values for argument 'x'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[47]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mdouble_param\u001b[49m\u001b[43m(\u001b[49m\u001b[32;43m10\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43m{\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mx\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m20\u001b[39;49m\u001b[43m}\u001b[49m\u001b[43m)\u001b[49m\n", - "\u001b[31mTypeError\u001b[39m: double_param() got multiple values for argument 'x'" - ] - } - ], - "source": [ - "double_param(10, **{\"x\": 20})" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c6085927-6fcf-465f-89d9-9bb8c37c9a68", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "533e7ace-5b76-425b-af1d-7d91fad62155", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 48, - "id": "d591834c-412a-4644-9ce2-b91eb979d1bb", - "metadata": {}, - "outputs": [], - "source": [ - "def double_param_valid(x, /, **kwargs):\n", - " return x, kwargs" - ] - }, - { - "cell_type": "code", - "execution_count": 50, - "id": "709b165f-df48-4904-a5ab-7d9e2fa33326", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(10, {'x': 20})" - ] - }, - "execution_count": 50, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "double_param_valid(10, x=20)" - ] - }, - { - "cell_type": "code", - "execution_count": 52, - "id": "3b0d65ae-9167-4792-92d1-9cb6a2c46054", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(10, {'x': 20})" - ] - }, - "execution_count": 52, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "double_param_valid(10, **{\"x\": 20})" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "88afc162-afed-453d-b98d-6c3d6bd8beee", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "441063c9-e278-480a-a8a0-071e704d6112", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4a04fead-5aa2-41d3-9e61-f5fd3c0ea19f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 66, - "id": "29bfc29a-5cfe-4317-96f9-17f3abaf3871", - "metadata": {}, - "outputs": [], - "source": [ - "def append_val(val: int, nums: list[int] = []) -> None:\n", - " nums.append(val)\n", - " return nums" - ] - }, - { - "cell_type": "code", - "execution_count": 58, - "id": "8b6dca58-6db7-4bf1-9d0f-1be5ae7c8a85", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[10]" - ] - }, - "execution_count": 58, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "append_val(10)" - ] - }, - { - "cell_type": "code", - "execution_count": 59, - "id": "97360958-eaae-420f-a06a-f6e80c364387", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[10, 20, 30, 40]" - ] - }, - "execution_count": 59, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "append_val(40, [10, 20, 30])" - ] - }, - { - "cell_type": "code", - "execution_count": 60, - "id": "e730c50e-cccc-4b29-b19d-08500e09b964", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[10, 20]" - ] - }, - "execution_count": 60, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "append_val(20)" - ] - }, - { - "cell_type": "code", - "execution_count": 62, - "id": "c88c85d6-a837-4be8-b9e1-5e0ae0fcb6b4", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 62, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "id(append_val(20)) == id(append_val(30))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "dec27461-c333-4715-9663-973659c3549a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 63, - "id": "85328874-d6b8-4b1b-ba72-46ed59f33cef", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "False" - ] - }, - "execution_count": 63, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "id(append_val(40, [10, 20, 30])) == id(append_val(30))" - ] - }, - { - "cell_type": "code", - "execution_count": 64, - "id": "b13a5096-b1f2-4692-abd4-dc9d2b545851", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[10, 20, 20, 20, 30, 30, 30]" - ] - }, - "execution_count": 64, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "append_val(30)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a62e9a61-ea0f-4601-9201-d56553cbe123", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a2101bc6-3bf8-4237-96e5-7d928e0a985d", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 67, - "id": "d7c20291-b982-4a70-bc91-e4f1f4294ec1", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "create_list\n", - "create_list\n" - ] - } - ], - "source": [ - "def create_list(init=[\"start\"]):\n", - " print(\"create_list\")\n", - " return init\n", - "\n", - "\n", - "def append_val_1(val: int, nums: list[int] = create_list()) -> None:\n", - " print(\"append_val_1 before {val=}, {nums=}\")\n", - " nums.append(val)\n", - " print(\"append_val_1 after {val=}, {nums=}\")\n", - " return nums\n", - "\n", - "\n", - "def append_val_2(val: int, nums: list[int] = create_list()) -> None:\n", - " print(\"append_val_2 before {val=}, {nums=}\")\n", - " nums.append(val)\n", - " print(\"append_val_2 after {val=}, {nums=}\")\n", - " return nums" - ] - }, - { - "cell_type": "code", - "execution_count": 68, - "id": "a7495d53-e98e-45b5-bc92-766c5bb51a23", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "append_val_1 before {val=}, {nums=}\n", - "append_val_1 after {val=}, {nums=}\n" - ] - }, - { - "data": { - "text/plain": [ - "['start', 10]" - ] - }, - "execution_count": 68, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "append_val_1(10)" - ] - }, - { - "cell_type": "code", - "execution_count": 69, - "id": "2458b40c-6f7e-4e66-9ca3-f05d084a183e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "append_val_1 before {val=}, {nums=}\n", - "append_val_1 after {val=}, {nums=}\n" - ] - }, - { - "data": { - "text/plain": [ - "['start', 10, 20]" - ] - }, - "execution_count": 69, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "append_val_1(20)" - ] - }, - { - "cell_type": "code", - "execution_count": 70, - "id": "59220a18-aa2d-4d3f-ba6a-d69e2ad53f2b", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "append_val_2 before {val=}, {nums=}\n", - "append_val_2 after {val=}, {nums=}\n" - ] - }, - { - "data": { - "text/plain": [ - "['start', 10, 20, 50]" - ] - }, - "execution_count": 70, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "append_val_2(50)" - ] - }, - { - "cell_type": "code", - "execution_count": 71, - "id": "d784f7dd-a711-492e-b926-a16de8892283", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "append_val_2 before {val=}, {nums=}\n", - "append_val_2 after {val=}, {nums=}\n" - ] - }, - { - "data": { - "text/plain": [ - "['start', 10, 20, 50, 60]" - ] - }, - "execution_count": 71, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "append_val_2(60)" - ] - }, - { - "cell_type": "code", - "execution_count": 72, - "id": "0b78eb3f-0287-4f96-96cb-26ea4787881e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "append_val_1 before {val=}, {nums=}\n", - "append_val_1 after {val=}, {nums=}\n" - ] - }, - { - "data": { - "text/plain": [ - "['start', 10, 20, 50, 60, 420]" - ] - }, - "execution_count": 72, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "append_val_1(420)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d6c31cca-7db1-408c-85da-dcf4becbd918", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 78, - "id": "be8d45d3-5da1-4f90-95fe-76991c997cb0", - "metadata": {}, - "outputs": [], - "source": [ - "def func1(val): # val = init: val -> PyObject(id=101, [1, 2])\n", - " val += val\n", - " print(f\"{val=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 79, - "id": "81e161bc-11fa-4c58-bad3-21b7296e9cb7", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "val=[1, 2, 1, 2]\n" - ] - } - ], - "source": [ - "init = [1, 2] # init -> PyObject(id=101, [1, 2])\n", - "\n", - "func1(init)" - ] - }, - { - "cell_type": "code", - "execution_count": 80, - "id": "6afa5549-c22e-4141-9e8e-dbed0a8134cf", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[1, 2, 1, 2]" - ] - }, - "execution_count": 80, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "init # init -> PyObject(id=101, [1, 2, 1, 2])" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ca331a09-eb16-437a-b6cf-1443ddeb99bf", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 84, - "id": "4be9fc95-099f-4771-a351-81790251e508", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "val='123123'\n" - ] - }, - { - "data": { - "text/plain": [ - "'123'" - ] - }, - "execution_count": 84, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "init = \"123\" # init -> PyObject(id=101, \"123\")\n", - "\n", - "func1(init) # val = init: val -> PyObject(id=101, \"123\")\n", - "# val += val: val -> PyObject(id=202, \"123123\")\n", - "\n", - "init" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8fe90eb5-5736-41e5-ad86-5ebbb55d831b", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "17f3445c-4695-4fda-a2ba-d49600de27f5", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6c56c317-3d82-49bc-b842-3d1e910a8a0d", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 81, - "id": "e2d6fe5b-5548-4220-8382-b17b0fb016c5", - "metadata": {}, - "outputs": [], - "source": [ - "def func2(val): # val = init: val -> PyObject(id=101, [1, 2])\n", - " val = val + val # val -> PyObject(id=202, [1, 2, 1, 2])\n", - " print(f\"{val=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 82, - "id": "aeff1b90-00dd-4194-8ba5-dd67757ccdbe", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "val=[1, 2, 1, 2]\n" - ] - } - ], - "source": [ - "init = [1, 2] # init -> PyObject(id=101, [1, 2])\n", - "\n", - "func2(init)" - ] - }, - { - "cell_type": "code", - "execution_count": 83, - "id": "8dc13c74-4aa3-41b7-8878-bf6b236c8d74", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[1, 2]" - ] - }, - "execution_count": 83, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "init # init -> PyObject(id=101, [1, 2])" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6dc336a0-f962-4e95-8952-ea78329ff41e", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 90, - "id": "ac30bb07-6537-4538-86ea-ffc02a3794d4", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "([0, -1, 1, -2, 2, -3, 3, -4, 4, -5], [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])" - ] - }, - "execution_count": 90, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "lst = list(range(-5, 5))\n", - "sorted(lst, key=lambda x: x * x), lst # O(n log n)" - ] - }, - { - "cell_type": "code", - "execution_count": 89, - "id": "6c992dd9-2263-4b61-99f0-381b0c371b16", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[0, -1, 1, -2, 2, -3, 3, -4, 4, -5]" - ] - }, - "execution_count": 89, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "lst = list(range(-5, 5))\n", - "lst.sort(key=lambda x: x * x)\n", - "lst" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1a10309d-346b-4a62-8ed4-fcf3ff7092a5", - "metadata": {}, - "outputs": [], - "source": [ - "def process_data(nums):\n", - " # nums.sort() | sorted(nums)\n", - " ..." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "33b95409-26e6-4659-846c-953e3077d37d", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fe80ce62-4da3-46a3-878a-f49e382c836f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 92, - "id": "29629bd4-0eb1-42ef-b30b-51b5999862a1", - "metadata": {}, - "outputs": [], - "source": [ - "functions = [lambda x: x + i for i in range(5)]" - ] - }, - { - "cell_type": "code", - "execution_count": 93, - "id": "d4fea364-afd5-45a1-80cd-a0f5fe26822d", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "False" - ] - }, - "execution_count": 93, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "functions[0] is functions[1]" - ] - }, - { - "cell_type": "code", - "execution_count": 95, - "id": "6b4bb7fa-7a3c-4b68-bb68-09cde4a298cf", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "24\n", - "24\n", - "24\n", - "24\n", - "24\n" - ] - } - ], - "source": [ - "for fn in functions:\n", - " print(fn(20))" - ] - }, - { - "cell_type": "code", - "execution_count": 96, - "id": "557d968c-e401-40fc-868c-03f1b32dba07", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "99" - ] - }, - "execution_count": 96, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "i" - ] - }, - { - "cell_type": "code", - "execution_count": 103, - "id": "64a65a8f-9e6d-4d2e-a73e-d9f6e96a0aeb", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "20\n", - "21\n", - "22\n", - "23\n", - "24\n", - "----\n", - "24\n", - "24\n", - "24\n", - "24\n", - "24\n" - ] - } - ], - "source": [ - "functions = []\n", - "\n", - "for i in range(5):\n", - " def fn(x):\n", - " return x + i\n", - " \n", - " print(fn(20))\n", - " functions.append(fn)\n", - "\n", - "print(\"----\")\n", - "\n", - "for fn in functions:\n", - " print(fn(20))" - ] - }, - { - "cell_type": "code", - "execution_count": 99, - "id": "a51b1442-32e7-4f0e-acb9-f9cdaf3fb472", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "4" - ] - }, - "execution_count": 99, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "i" - ] - }, - { - "cell_type": "code", - "execution_count": 100, - "id": "479d3bfa-0aae-4ee9-a911-ddba19400926", - "metadata": {}, - "outputs": [], - "source": [ - "i = 100" - ] - }, - { - "cell_type": "code", - "execution_count": 101, - "id": "318cefe7-a936-45b7-aa39-2afbf5b73e6a", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "120\n", - "120\n", - "120\n", - "120\n", - "120\n" - ] - } - ], - "source": [ - "for fn in functions:\n", - " print(fn(20))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a93f36a4-be53-4c2f-bcf2-7eb02f91678a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a7366b3a-e29b-4c1b-ac00-844c623aa339", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 104, - "id": "7e02739d-8b05-4d38-a7f2-349f81301ec3", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "20\n", - "21\n", - "22\n", - "23\n", - "24\n", - "----\n", - "20\n", - "21\n", - "22\n", - "23\n", - "24\n" - ] - } - ], - "source": [ - "functions = []\n", - "\n", - "for i in range(5):\n", - " def fn(x, add=i):\n", - " return x + add\n", - " \n", - " print(fn(20))\n", - " functions.append(fn)\n", - "\n", - "print(\"----\")\n", - "\n", - "for fn in functions:\n", - " print(fn(20))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5fa69d09-0c8e-419a-bf6e-7aa141236714", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7672c807-6400-454b-80ab-50163cd7053d", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 119, - "id": "468d0bfe-48c8-4549-b385-ffbbb5f9b59a", - "metadata": {}, - "outputs": [], - "source": [ - "import time\n", - "from functools import wraps" - ] - }, - { - "cell_type": "code", - "execution_count": 113, - "id": "2de693e2-9df9-4031-9d49-3df16524c49f", - "metadata": {}, - "outputs": [], - "source": [ - "def timeit(fn):\n", - " def inner(*args, **kwargs):\n", - " start = time.time()\n", - " try:\n", - " res = fn(*args, **kwargs)\n", - " finally:\n", - " finish = time.time()\n", - " print(f\"Measure: {finish - start}!\")\n", - " return res\n", - " return inner" - ] - }, - { - "cell_type": "code", - "execution_count": 114, - "id": "f08ca597-359e-4833-9ae2-df709e27f858", - "metadata": {}, - "outputs": [], - "source": [ - "@timeit\n", - "def add(a, b):\n", - " print(\"add\", a, b)\n", - " return a + b" - ] - }, - { - "cell_type": "code", - "execution_count": 115, - "id": "cabb8061-d921-465c-84c6-f3df8f0b5ad7", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "add 1 2\n", - "Measure: 0.0002989768981933594!\n" - ] - }, - { - "data": { - "text/plain": [ - "3" - ] - }, - "execution_count": 115, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "add(1, 2)" - ] - }, - { - "cell_type": "code", - "execution_count": 116, - "id": "2d335057-6f38-4e5a-ac5a-1677ff43bc18", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - ".inner(*args, **kwargs)>" - ] - }, - "execution_count": 116, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "add" - ] - }, - { - "cell_type": "code", - "execution_count": 117, - "id": "7e4b047e-4aa2-4f1c-a389-5d5cdd7d6bad", - "metadata": {}, - "outputs": [], - "source": [ - "def add(a, b):\n", - " print(\"add\", a, b)\n", - " return a + b" - ] - }, - { - "cell_type": "code", - "execution_count": 138, - "id": "d24f38f6-0096-412b-85d3-35789265d2b8", - "metadata": {}, - "outputs": [], - "source": [ - "x = 42\n", - "\n", - "def timeit(fn):\n", - " y = 57\n", - " @wraps(fn)\n", - " def inner(*args, **kwargs):\n", - " start = time.time()\n", - " try:\n", - " res = fn(*args, **kwargs) + x + y\n", - " finally:\n", - " finish = time.time()\n", - " print(f\"Measure: {finish - start}!\")\n", - " return res\n", - " return inner" - ] - }, - { - "cell_type": "code", - "execution_count": 139, - "id": "da19ccc9-4d3f-46d6-a162-13d6398f96c7", - "metadata": {}, - "outputs": [], - "source": [ - "@timeit\n", - "def add(a, b):\n", - " print(\"add\", a, b)\n", - " return a + b" - ] - }, - { - "cell_type": "code", - "execution_count": 122, - "id": "b7d3912f-584c-4d7e-9107-e5a658365368", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "add 1 2\n", - "Measure: 5.3882598876953125e-05!\n" - ] - }, - { - "data": { - "text/plain": [ - "3" - ] - }, - "execution_count": 122, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "add(1, 2)" - ] - }, - { - "cell_type": "code", - "execution_count": 123, - "id": "57d777c2-54d9-4854-b8fd-5dabfde340cb", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 123, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "add" - ] - }, - { - "cell_type": "code", - "execution_count": 125, - "id": "f9227e93-90b2-4067-8f73-1e4cb5c229e0", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "add 1 2\n" - ] - }, - { - "data": { - "text/plain": [ - "3" - ] - }, - "execution_count": 125, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "add.__wrapped__(1, 2)" - ] - }, - { - "cell_type": "code", - "execution_count": 126, - "id": "b3d9e743-9753-42a5-ba80-9920cb3f106d", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 126, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "add.__wrapped__" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "08fb4c63-fb3a-460b-8435-d7f996527e38", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 141, - "id": "312926c9-0e25-4bec-b3f1-eca333d3910f", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "57" - ] - }, - "execution_count": 141, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "add.__closure__[1].cell_contents" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8ceab6be-33d0-4b1b-b387-7f539bbe4ce5", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3e886396-8cf6-4534-a360-bb8c0d85b7a7", - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.13.2" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/lesson-02/homework.md b/lesson-02/homework.md deleted file mode 100644 index b549ae4..0000000 --- a/lesson-02/homework.md +++ /dev/null @@ -1,108 +0,0 @@ -# Домашнее задание #02 (функции) - -### 1. Функция для обработки json -Функция для обработки должна принимать параметры: -- строку с json; -- список ключей, которые необходимо обработать; -- список токенов, которые нужно найти; -- функцию-обработчик ключа и токена. - -json для задания всегда имеет вид словаря с ключами и значениями из строк. Строки-значения в json содержат произвольное число пробелов в качестве разделителей слов, знаков препинания нет. - -Все токены и ключи состоят только из букв и цифр без пробельных символов. - -Функция парсит строку с json библиотечными средствами. -Для каждого ключа json, который совпадает с одним из переданных ключей для обработки, функция должна искать вхождения токенов в строку-значение по данному ключу. -Для каждого найденного токена должна быть вызвана функция-обработчик с ключом и токеном. - -Поиск ключей должен зависеть от регистра, а поиск токенов должен быть регистронезависимым. - - -```py -def process_json( - json_str: str, - required_keys: list[str] | None = None, - tokens: list[str] | None = None, - callback: Callable[[str, str], Any] | None = None, -) -> None: - ... - - -# например: -json_str = '{"key1": "Word1 word2", "key2": "word2 word3"}' -required_keys = ["key1", "KEY2"] -tokens = ["WORD1", "word2"] - -process_json(json_str, required_keys, tokens, lambda key, token: f"{key=}, {token=}") - -# выведет: -# key="key1", token="WORD1" -# key="key1", token="word2" -``` - -### 2. Параметризуемый декоратор для логирования вызовов и перезапуска функций в случае ошибок -Декоратор `retry_deco` должен: -- принимать опциональными параметрами число перезапусков декорируемой функции и список ожидаемых классов исключений; -- при вызове функции логировать (выводить) название функции, все переданные ей аргументы, номер попытки перезапуска, результат работы функции и ошибку, если было выброшено исключение; - формат логирования произвольный (например, функция и аргументы один раз, а номер попытки и исключение/результат сколько потребуется); -- в случае исключения при выполнении функции декоратор должен выполнить новую попытку запуска функции, пока не достигнет заданного числа перезапусков; - если исключение из списка ожидаемых классов исключений (параметр декоратора), то перезапускать функцию не надо, тк исключения из списка это нормальный режим работы декорируемой функции. - -```py -def retry_deco(...): - ... - - -@retry_deco(3) -def add(a, b): - return a + b - - -add(4, 2) -# run "add" with positional args = (4, 2), attempt = 1, result = 6 - -add(4, b=3) -# run "add" with positional args = (4,), keyword kwargs = {"b": 3}, attempt = 1, result = 7 - - -@retry_deco(3) -def check_str(value=None): - if value is None: - raise ValueError() - - return isinstance(value, str) - - -check_str(value="123") -# run "check_str" with keyword kwargs = {"value": "123"}, attempt = 1, result = True - -check_str(value=1) -# run "check_str" with keyword kwargs = {"value": 1}, attempt = 1, result = False - -check_str(value=None) -# run "check_str" with keyword kwargs = {"value": None}, attempt = 1, exception = ValueError -# run "check_str" with keyword kwargs = {"value": None}, attempt = 2, exception = ValueError -# run "check_str" with keyword kwargs = {"value": None}, attempt = 3, exception = ValueError - - -@retry_deco(2, [ValueError]) -def check_int(value=None): - if value is None: - raise ValueError() - - return isinstance(value, int) - -check_int(value=1) -# run "check_int" with keyword kwargs = {"value": 1}, attempt = 1, result = True - -check_int(value=None) -# run "check_int" with keyword kwargs = {"value": None}, attempt = 1, exception = ValueError # нет перезапуска - -``` - -### 3. Тесты в отдельном модуле для каждого пункта - -### 4. Зеленый пайплайн в репе -Обязательно: тесты, покрытие, flake8, pylint. -Опционально можно добавить другие инструменты, например, mypy и black. -Покрытие тестов должно составлять не менее 90%. diff --git a/lesson-02/lesson-02.pdf b/lesson-02/lesson-02.pdf deleted file mode 100644 index 864cc14..0000000 Binary files a/lesson-02/lesson-02.pdf and /dev/null differ diff --git a/lesson-03/class_03.ipynb b/lesson-03/class_03.ipynb deleted file mode 100644 index eb2a1d2..0000000 --- a/lesson-03/class_03.ipynb +++ /dev/null @@ -1,2504 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "id": "b13a94ae-30bc-466e-bb55-f0dddea3cc3c", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'__name__': '__main__',\n", - " '__doc__': 'Automatically created module for IPython interactive environment',\n", - " '__package__': None,\n", - " '__loader__': None,\n", - " '__spec__': None,\n", - " '__builtin__': ,\n", - " '__builtins__': ,\n", - " '_ih': ['', 'globals()'],\n", - " '_oh': {},\n", - " '_dh': [PosixPath('/Users/g.kandaurov/projects/hse_deep_python_autumn_2025/lesson-03')],\n", - " 'In': ['', 'globals()'],\n", - " 'Out': {},\n", - " 'get_ipython': >,\n", - " 'exit': ,\n", - " 'quit': ,\n", - " 'open': ,\n", - " '_': '',\n", - " '__': '',\n", - " '___': '',\n", - " '__session__': '/Users/g.kandaurov/projects/hse_deep_python_autumn_2025/lesson-03/Untitled.ipynb',\n", - " '_i': '',\n", - " '_ii': '',\n", - " '_iii': '',\n", - " '_i1': 'globals()'}" - ] - }, - "execution_count": 1, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "globals()" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "62b42460-7b7e-424f-9a32-229dc9748064", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'__name__': '__main__',\n", - " '__doc__': 'Automatically created module for IPython interactive environment',\n", - " '__package__': None,\n", - " '__loader__': None,\n", - " '__spec__': None,\n", - " '__builtin__': ,\n", - " '__builtins__': ,\n", - " '_ih': ['', 'globals()', 'locals()'],\n", - " '_oh': {1: {...}},\n", - " '_dh': [PosixPath('/Users/g.kandaurov/projects/hse_deep_python_autumn_2025/lesson-03')],\n", - " 'In': ['', 'globals()', 'locals()'],\n", - " 'Out': {1: {...}},\n", - " 'get_ipython': >,\n", - " 'exit': ,\n", - " 'quit': ,\n", - " 'open': ,\n", - " '_': {...},\n", - " '__': '',\n", - " '___': '',\n", - " '__session__': '/Users/g.kandaurov/projects/hse_deep_python_autumn_2025/lesson-03/Untitled.ipynb',\n", - " '_i': 'globals()',\n", - " '_ii': '',\n", - " '_iii': '',\n", - " '_i1': 'globals()',\n", - " '_1': {...},\n", - " '_i2': 'locals()'}" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "locals()" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "f9f21ae1-b0a6-4061-a322-93f7a650c5ae", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "globals() is locals()" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "50e99a4b-aff8-41a0-a5d4-aefe5ed76061", - "metadata": {}, - "outputs": [], - "source": [ - "def update_global(name, val):\n", - " print(f\"{locals()=}\")\n", - " locals()[\"loc_\" + name] = val\n", - " print(f\"{locals()=}\")\n", - "\n", - " globals()[name] = val" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "51be1938-774f-4a2d-a93d-6a47c3ccf9ab", - "metadata": {}, - "outputs": [ - { - "ename": "NameError", - "evalue": "name 'qwerty' is not defined", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mNameError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[6]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mqwerty\u001b[49m\n", - "\u001b[31mNameError\u001b[39m: name 'qwerty' is not defined" - ] - } - ], - "source": [ - "qwerty" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "3fe96c85-dc4b-4892-b97a-9f92cd9782e0", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "locals()={'name': 'qwerty', 'val': 123}\n", - "locals()={'name': 'qwerty', 'val': 123}\n" - ] - } - ], - "source": [ - "update_global(\"qwerty\", 123)" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "e28db253-1b6d-4a2f-9e6c-3639c3cb001f", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "123" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "qwerty" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "a528f91c-53d1-47df-b1bc-cd93fb58bf41", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "123" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "globals()[\"qwerty\"]" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "fe9ef4eb-be36-46dc-9af8-58b815743df6", - "metadata": {}, - "outputs": [], - "source": [ - "globals()[\"@@asdf\"] = 3456" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "6201ef17-2844-430e-97b3-9d90f5898981", - "metadata": {}, - "outputs": [ - { - "ename": "SyntaxError", - "evalue": "invalid syntax (2276178104.py, line 1)", - "output_type": "error", - "traceback": [ - " \u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[13]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[31m \u001b[39m\u001b[31m@@asdf\u001b[39m\n ^\n\u001b[31mSyntaxError\u001b[39m\u001b[31m:\u001b[39m invalid syntax\n" - ] - } - ], - "source": [ - "@@asdf" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "c03ff2aa-af71-4f58-bf53-1161d466b3dd", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "3456" - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "globals()[\"@@asdf\"]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "641ec5e0-042f-401f-8cac-3e2fdf63bab7", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "beb89c80-74ee-45ba-9f0a-cd2865c41dab", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "da7034a4-24a4-416a-8df1-5061bb5992cb", - "metadata": {}, - "outputs": [], - "source": [ - "def update_default(a, x=[]):\n", - " x.append(a)\n", - " return x" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "9a8fe8fb-402b-4ae9-8148-d6f30bccc884", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "([10, 20], [10, 20])" - ] - }, - "execution_count": 16, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "update_default(10), update_default(20)" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "1550f5c6-8b1d-46a8-ae75-edb1feee3474", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "([10, 20],)" - ] - }, - "execution_count": 17, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "update_default.__defaults__" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "e0891b40-afa9-419b-9aa1-da7c5cf47941", - "metadata": {}, - "outputs": [], - "source": [ - "update_default.__defaults__[0].append(40)" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "4fdd7597-330e-48f6-865e-dbf9720b7ea5", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[10, 20, 40, 50]" - ] - }, - "execution_count": 19, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "update_default(50)" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "24fe6fdc-a7a7-4ef5-9ea5-9503a106cb9e", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "'tuple' object does not support item assignment", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[20]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mupdate_default\u001b[49m\u001b[43m.\u001b[49m\u001b[34;43m__defaults__\u001b[39;49m\u001b[43m[\u001b[49m\u001b[32;43m0\u001b[39;49m\u001b[43m]\u001b[49m = [\u001b[32m1\u001b[39m, \u001b[32m2\u001b[39m, \u001b[32m3\u001b[39m]\n", - "\u001b[31mTypeError\u001b[39m: 'tuple' object does not support item assignment" - ] - } - ], - "source": [ - "update_default.__defaults__[0] = [1, 2, 3]" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "d2d95deb-1d6d-45a9-9de1-0b4f224b1961", - "metadata": {}, - "outputs": [], - "source": [ - "update_default.__defaults__ = ([1, 2, 3],)" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "f6f497eb-4f88-4726-a94b-534623470862", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[1, 2, 3, 50]" - ] - }, - "execution_count": 22, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "update_default(50)" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "e2cd38e9-6175-44cc-8b46-b6aeace1522e", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[1, 2, 3, 50, 30]" - ] - }, - "execution_count": 23, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "update_default(30)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8224851b-ed06-4aa3-af93-7860cb1cc919", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1f164cd1-c3e1-4296-b9ac-a1134e712f03", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "e1b00925-4d69-40cf-b8c5-9c824001b027", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "before calc: counter=0\n" - ] - }, - { - "ename": "UnboundLocalError", - "evalue": "cannot access local variable 'counter' where it is not associated with a value", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mUnboundLocalError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[24]\u001b[39m\u001b[32m, line 9\u001b[39m\n\u001b[32m 5\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mcalc: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlocals\u001b[39m()\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m 7\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mbefore calc: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m----> \u001b[39m\u001b[32m9\u001b[39m \u001b[43mcalc\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 11\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mafter calc: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[24]\u001b[39m\u001b[32m, line 4\u001b[39m, in \u001b[36mcalc\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m 3\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mcalc\u001b[39m():\n\u001b[32m----> \u001b[39m\u001b[32m4\u001b[39m \u001b[43mcounter\u001b[49m += \u001b[32m1\u001b[39m\n\u001b[32m 5\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mcalc: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlocals\u001b[39m()\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", - "\u001b[31mUnboundLocalError\u001b[39m: cannot access local variable 'counter' where it is not associated with a value" - ] - } - ], - "source": [ - "counter = 0\n", - "\n", - "def calc():\n", - " counter += 1\n", - " print(f\"calc: {counter=}, {locals()=}\")\n", - "\n", - "print(f\"before calc: {counter=}\")\n", - "\n", - "calc()\n", - "\n", - "print(f\"after calc: {counter=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "60c2a691-1682-46b9-bec1-19dad34e56d1", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "7733bd76-2a26-455e-9fa0-0b07bed5bdae", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "before calc: counter=0\n", - "calc: counter=0, locals()={}\n", - "after calc: counter=0\n" - ] - } - ], - "source": [ - "counter = 0\n", - "\n", - "def calc():\n", - " print(f\"calc: {counter=}, {locals()=}\")\n", - "\n", - "print(f\"before calc: {counter=}\")\n", - "\n", - "calc()\n", - "\n", - "print(f\"after calc: {counter=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "6a2c8ac7-bff1-4688-be98-9458013eaedc", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "before calc: counter=[]\n", - "calc: counter=[1], locals()={}\n", - "after calc: counter=[1]\n" - ] - } - ], - "source": [ - "counter = []\n", - "\n", - "def calc():\n", - " counter.append(1)\n", - " print(f\"calc: {counter=}, {locals()=}\")\n", - "\n", - "print(f\"before calc: {counter=}\")\n", - "\n", - "calc()\n", - "\n", - "print(f\"after calc: {counter=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9f04c583-5e4f-4820-a951-c73d07b1f530", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "e09bb6d2-f030-4768-89c0-19bc7e91cab5", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "before calc: counter=[]\n" - ] - }, - { - "ename": "UnboundLocalError", - "evalue": "cannot access local variable 'counter' where it is not associated with a value", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mUnboundLocalError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[27]\u001b[39m\u001b[32m, line 9\u001b[39m\n\u001b[32m 5\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mcalc: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlocals\u001b[39m()\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m 7\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mbefore calc: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m----> \u001b[39m\u001b[32m9\u001b[39m \u001b[43mcalc\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 11\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mafter calc: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[27]\u001b[39m\u001b[32m, line 4\u001b[39m, in \u001b[36mcalc\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m 3\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mcalc\u001b[39m():\n\u001b[32m----> \u001b[39m\u001b[32m4\u001b[39m counter = \u001b[43mcounter\u001b[49m + [\u001b[32m1\u001b[39m]\n\u001b[32m 5\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mcalc: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlocals\u001b[39m()\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", - "\u001b[31mUnboundLocalError\u001b[39m: cannot access local variable 'counter' where it is not associated with a value" - ] - } - ], - "source": [ - "counter = []\n", - "\n", - "def calc():\n", - " counter = counter + [1]\n", - " print(f\"calc: {counter=}, {locals()=}\")\n", - "\n", - "print(f\"before calc: {counter=}\")\n", - "\n", - "calc()\n", - "\n", - "print(f\"after calc: {counter=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "66c22556-649e-4cf7-94d3-723d53184aec", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d19ed055-430e-41a4-a864-fe9f1a37c22c", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "fb3a6ada-525c-49e0-bba7-8c23c0a1c98c", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "before calc: counter=[]\n", - "calc: counter=[1], locals()={'counter': [1]}\n", - "after calc: counter=[]\n" - ] - } - ], - "source": [ - "counter = []\n", - "\n", - "def calc():\n", - " counter = [1]\n", - " print(f\"calc: {counter=}, {locals()=}\")\n", - "\n", - "print(f\"before calc: {counter=}\")\n", - "\n", - "calc()\n", - "\n", - "print(f\"after calc: {counter=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "3f1877ce-22b5-4699-b429-7aadf06c756d", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "before calc: counter=0\n", - "calc: counter=1, locals()={}\n", - "after calc: counter=1\n" - ] - } - ], - "source": [ - "counter = 0\n", - "#counter += 1\n", - "\n", - "def calc():\n", - " global counter\n", - " counter += 1\n", - " print(f\"calc: {counter=}, {locals()=}\")\n", - "\n", - "print(f\"before calc: {counter=}\")\n", - "\n", - "calc()\n", - "\n", - "print(f\"after calc: {counter=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8c57398d-fd6d-467e-807d-dfb8f8d57a8e", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8d54e57d-b5c1-44bf-913f-be94b2ae75da", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4589ca23-15c9-4a43-b042-576dc2607867", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "95d88b27-e886-482b-ac52-5a2ae8a997e3", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "before calc: counter=99\n", - "before inner: counter=1, locals()={'inner': .inner at 0x10c3107c0>, 'counter': 1}\n", - "inner: counter=1, locals()={'counter': 1}\n", - "after inner: counter=1, locals()={'inner': .inner at 0x10c3107c0>, 'counter': 1}\n", - "after calc: counter=99\n" - ] - } - ], - "source": [ - "counter = 99\n", - "\n", - "def calc():\n", - " counter = 1\n", - "\n", - " def inner():\n", - " print(f\"inner: {counter=}, {locals()=}\")\n", - "\n", - " print(f\"before inner: {counter=}, {locals()=}\")\n", - " inner()\n", - " print(f\"after inner: {counter=}, {locals()=}\")\n", - "\n", - "\n", - "print(f\"before calc: {counter=}\")\n", - "\n", - "calc()\n", - "\n", - "print(f\"after calc: {counter=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e423e06e-6edd-4cdf-9f4c-b4c62ca08f87", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "e0ddba89-8526-4baf-ad08-892a53c21011", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "before calc: counter=99\n", - "before inner: counter=1, locals()={'counter': 1, 'inner': .inner at 0x10c311760>}\n" - ] - }, - { - "ename": "UnboundLocalError", - "evalue": "cannot access local variable 'counter' where it is not associated with a value", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mUnboundLocalError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[32]\u001b[39m\u001b[32m, line 17\u001b[39m\n\u001b[32m 12\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mafter inner: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlocals\u001b[39m()\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m 15\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mbefore calc: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m---> \u001b[39m\u001b[32m17\u001b[39m \u001b[43mcalc\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 19\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mafter calc: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[32]\u001b[39m\u001b[32m, line 11\u001b[39m, in \u001b[36mcalc\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m 8\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33minner: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlocals\u001b[39m()\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m 10\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mbefore inner: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlocals\u001b[39m()\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m---> \u001b[39m\u001b[32m11\u001b[39m \u001b[43minner\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 12\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mafter inner: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlocals\u001b[39m()\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[32]\u001b[39m\u001b[32m, line 7\u001b[39m, in \u001b[36mcalc..inner\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m 6\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34minner\u001b[39m():\n\u001b[32m----> \u001b[39m\u001b[32m7\u001b[39m \u001b[43mcounter\u001b[49m += \u001b[32m1\u001b[39m\n\u001b[32m 8\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33minner: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcounter\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlocals\u001b[39m()\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", - "\u001b[31mUnboundLocalError\u001b[39m: cannot access local variable 'counter' where it is not associated with a value" - ] - } - ], - "source": [ - "counter = 99\n", - "\n", - "def calc():\n", - " counter = 1\n", - "\n", - " def inner():\n", - " counter += 1\n", - " print(f\"inner: {counter=}, {locals()=}\")\n", - "\n", - " print(f\"before inner: {counter=}, {locals()=}\")\n", - " inner()\n", - " print(f\"after inner: {counter=}, {locals()=}\")\n", - "\n", - "\n", - "print(f\"before calc: {counter=}\")\n", - "\n", - "calc()\n", - "\n", - "print(f\"after calc: {counter=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "3b4edf25-2c80-40ed-a4c0-aaea7b1e263a", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "before calc: counter=99\n", - "before inner: counter=1, locals()={'counter': 1, 'inner': .inner at 0x10c35e0c0>}\n", - "inner: counter=42, locals()={'counter': 42}\n", - "after inner: counter=1, locals()={'counter': 1, 'inner': .inner at 0x10c35e0c0>}\n", - "after calc: counter=99\n" - ] - } - ], - "source": [ - "counter = 99\n", - "\n", - "def calc():\n", - " counter = 1\n", - "\n", - " def inner():\n", - " counter = 42\n", - " print(f\"inner: {counter=}, {locals()=}\")\n", - "\n", - " print(f\"before inner: {counter=}, {locals()=}\")\n", - " inner()\n", - " print(f\"after inner: {counter=}, {locals()=}\")\n", - "\n", - "\n", - "print(f\"before calc: {counter=}\")\n", - "\n", - "calc()\n", - "\n", - "print(f\"after calc: {counter=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "947dc83f-da66-44a2-9e13-b0b2dff258dc", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "before calc: counter=99\n", - "before inner: counter=1, locals()={'inner': .inner at 0x10c35dda0>, 'counter': 1}\n", - "inner: counter=42, locals()={'counter': 42}\n", - "after inner: counter=42, locals()={'inner': .inner at 0x10c35dda0>, 'counter': 42}\n", - "after calc: counter=99\n" - ] - } - ], - "source": [ - "counter = 99\n", - "\n", - "def calc():\n", - " counter = 1\n", - "\n", - " def inner():\n", - " nonlocal counter\n", - " counter = 42\n", - " print(f\"inner: {counter=}, {locals()=}\")\n", - "\n", - " print(f\"before inner: {counter=}, {locals()=}\")\n", - " inner()\n", - " print(f\"after inner: {counter=}, {locals()=}\")\n", - "\n", - "\n", - "print(f\"before calc: {counter=}\")\n", - "\n", - "calc()\n", - "\n", - "print(f\"after calc: {counter=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "6409e07f-5fd1-4bfb-ac9b-817e930b1276", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "before calc: counter=99\n", - "before inner: counter=1, locals()={'inner': .inner at 0x10c35dd00>, 'counter': 1}\n", - "inner: counter=1, locals()={'counter': 1}\n", - "after inner: counter=1, locals()={'inner': .inner at 0x10c35dd00>, 'counter': 1}\n", - "after calc: counter=99\n" - ] - } - ], - "source": [ - "counter = 99\n", - "\n", - "def calc():\n", - " counter = 1\n", - "\n", - " def inner():\n", - " global not_exist\n", - " not_exist = 42\n", - " print(f\"inner: {counter=}, {locals()=}\")\n", - "\n", - " print(f\"before inner: {counter=}, {locals()=}\")\n", - " inner()\n", - " print(f\"after inner: {counter=}, {locals()=}\")\n", - "\n", - "\n", - "print(f\"before calc: {counter=}\")\n", - "\n", - "calc()\n", - "\n", - "print(f\"after calc: {counter=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "0a909fc5-78e7-46a0-9f24-3c97456b006a", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "42" - ] - }, - "execution_count": 37, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "not_exist" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "78ff9d18-aa9d-44d8-b4a4-2658162a1147", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "a62d767e-38e5-4a37-83b2-c380d890c1d0", - "metadata": {}, - "outputs": [], - "source": [ - "import time\n", - "from functools import wraps" - ] - }, - { - "cell_type": "code", - "execution_count": 55, - "id": "016953e6-c544-4a02-9709-3595365035c6", - "metadata": {}, - "outputs": [], - "source": [ - "def measure_time(fn):\n", - " total_sum = 0\n", - " total_count = 0\n", - "\n", - " @wraps(fn)\n", - " def inner(*args, **kwargs):\n", - " nonlocal total_sum\n", - " nonlocal total_count\n", - " \n", - " t1 = time.time()\n", - " try:\n", - " return fn(*args, **kwargs)\n", - " finally:\n", - " t2 = time.time()\n", - "\n", - " total_sum += t2 - t1 # total_sum = total_sum + t2 - t1\n", - " total_count += 1\n", - " \n", - " mean = total_sum / total_count\n", - " print(f\"{fn.__name__} time={t2 - t1}, {mean=}\")\n", - "\n", - " return inner\n", - "\n", - "\n", - "@measure_time\n", - "def fn_sleep(n):\n", - " time.sleep(n)\n" - ] - }, - { - "cell_type": "code", - "execution_count": 56, - "id": "c6ac45e9-0f24-4631-83c0-be7847e33864", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "fn_sleep time=1.0047900676727295, mean=1.0047900676727295\n" - ] - } - ], - "source": [ - "fn_sleep(1)" - ] - }, - { - "cell_type": "code", - "execution_count": 57, - "id": "81c481bf-0a6f-4b33-978e-9555aa88a7cd", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "fn_sleep time=0.1044168472290039, mean=0.5546034574508667\n" - ] - } - ], - "source": [ - "fn_sleep(0.1)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8ccc8692-31eb-4101-9772-c155e8b743d8", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "dcd1d41b-ceb0-4642-a971-2d7ea553e288", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3f78edd1-8836-47b3-807f-5f269fe9ff2a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9f1dc6b3-8e1a-458d-bf52-6f5a6a19d376", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1658787f-592f-48d4-8107-0a95c72a9c15", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a044d684-25b5-4533-a5bf-e989ae53d854", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "400aa611-4707-4aca-aa70-1d05bef58a6a", - "metadata": {}, - "source": [ - "# Class" - ] - }, - { - "cell_type": "code", - "execution_count": 60, - "id": "17ecb5c9-fe00-4703-89f1-71fef08fde2c", - "metadata": {}, - "outputs": [], - "source": [ - "class ClassAttr:\n", - " name = \"cls_name\"\n", - " __cls_private = \"cls_private\"\n", - "\n", - " __custom_name__ = \"custom_name\" # not recommend (!)\n", - "\n", - " def __custom_init__(self, val): # not recommend (!)\n", - " pass\n", - "\n", - " def __init__(self, val):\n", - " self.val = val\n", - " self._protected = \"protected\"\n", - " self.__private = \"private\"\n", - "\n", - " def print(self):\n", - " print(\n", - " f\"{self.val=}, {self._protected=}, {self.__private=}, \"\n", - " f\"{self.name=}, {self.__cls_private=}\"\n", - " )\n", - "\n", - " def print_new(self):\n", - " print(f\"{self.__private_3=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 58, - "id": "813bc0fb-ef3c-431a-a6df-8232ae22d22b", - "metadata": {}, - "outputs": [], - "source": [ - "def calc():\n", - " map = 42\n", - " print(map)" - ] - }, - { - "cell_type": "code", - "execution_count": 61, - "id": "98b43286-29fe-410b-87c8-da40f552a1fc", - "metadata": {}, - "outputs": [], - "source": [ - "obj = ClassAttr(10)" - ] - }, - { - "cell_type": "code", - "execution_count": 62, - "id": "4a7519b9-127e-4c01-965f-d068fb84f440", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'custom_name'" - ] - }, - "execution_count": 62, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.__custom_name__" - ] - }, - { - "cell_type": "code", - "execution_count": 63, - "id": "8999e759-5ba2-4e5d-bac5-55df3dcf2012", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'custom_name'" - ] - }, - "execution_count": 63, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ClassAttr.__custom_name__" - ] - }, - { - "cell_type": "code", - "execution_count": 64, - "id": "8a1da092-75b2-4511-9d7d-e78ae82c3fb5", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'val': 10, '_protected': 'protected', '_ClassAttr__private': 'private'}" - ] - }, - "execution_count": 64, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 65, - "id": "ce0bce85-3bd6-42ca-a14d-83c1e0034a4b", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(10, 'protected')" - ] - }, - "execution_count": 65, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.val, obj._protected" - ] - }, - { - "cell_type": "code", - "execution_count": 66, - "id": "1c254919-612e-4375-b626-8cf1407febad", - "metadata": {}, - "outputs": [ - { - "ename": "AttributeError", - "evalue": "'ClassAttr' object has no attribute '__private'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[66]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mobj\u001b[49m\u001b[43m.\u001b[49m\u001b[43m__private\u001b[49m\n", - "\u001b[31mAttributeError\u001b[39m: 'ClassAttr' object has no attribute '__private'" - ] - } - ], - "source": [ - "obj.__private" - ] - }, - { - "cell_type": "code", - "execution_count": 67, - "id": "554deab0-f545-4a30-a882-3d6360ae4596", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'private'" - ] - }, - "execution_count": 67, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj._ClassAttr__private" - ] - }, - { - "cell_type": "code", - "execution_count": 77, - "id": "f4e6a02b-419c-40e2-8830-de6dc007c6f8", - "metadata": {}, - "outputs": [], - "source": [ - "obj._ClassAttr__private = \"updated priv\"" - ] - }, - { - "cell_type": "code", - "execution_count": 78, - "id": "95539454-b3f2-4136-8831-611761028325", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "self.val=10, self._protected='protected', self.__private='updated priv', self.name='cls_name', self.__cls_private='cls_private'\n" - ] - } - ], - "source": [ - "obj.print()" - ] - }, - { - "cell_type": "code", - "execution_count": 79, - "id": "47a97a23-c823-4410-8227-6e4218e293ea", - "metadata": {}, - "outputs": [ - { - "ename": "AttributeError", - "evalue": "'ClassAttr' object has no attribute '_ClassAttr__private_3'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[79]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mobj\u001b[49m\u001b[43m.\u001b[49m\u001b[43mprint_new\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[60]\u001b[39m\u001b[32m, line 22\u001b[39m, in \u001b[36mClassAttr.print_new\u001b[39m\u001b[34m(self)\u001b[39m\n\u001b[32m 21\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mprint_new\u001b[39m(\u001b[38;5;28mself\u001b[39m):\n\u001b[32m---> \u001b[39m\u001b[32m22\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m__private_3\u001b[49m\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", - "\u001b[31mAttributeError\u001b[39m: 'ClassAttr' object has no attribute '_ClassAttr__private_3'" - ] - } - ], - "source": [ - "obj.print_new()" - ] - }, - { - "cell_type": "code", - "execution_count": 80, - "id": "6a734317-9364-4905-8874-aafc0b00f570", - "metadata": {}, - "outputs": [], - "source": [ - "obj._ClassAttr__private_3 = \"priv3\"" - ] - }, - { - "cell_type": "code", - "execution_count": 81, - "id": "14dc0111-8f28-480d-acf2-8da4075225a8", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "self.__private_3='priv3'\n" - ] - } - ], - "source": [ - "obj.print_new()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5c7fec8e-fc12-45e6-be1c-e11e8ec88540", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a6af5043-e8fd-474c-a9b8-1538c78a5fe4", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a614faad-f14e-4457-9787-ae9de7738173", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 69, - "id": "a388ed26-ae9e-45db-8c84-6865b208441c", - "metadata": {}, - "outputs": [], - "source": [ - "obj.__new_private = \"qwerty\"" - ] - }, - { - "cell_type": "code", - "execution_count": 70, - "id": "1c2601fd-9082-4f0c-8463-cbd93c6fa9b4", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'qwerty'" - ] - }, - "execution_count": 70, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.__new_private" - ] - }, - { - "cell_type": "code", - "execution_count": 82, - "id": "9c6b363e-e2fc-413f-bf22-8979ffc0d887", - "metadata": {}, - "outputs": [], - "source": [ - "obj._ClassAttr__book = \"literature\"" - ] - }, - { - "cell_type": "code", - "execution_count": 84, - "id": "3a3f70e5-484f-4864-8e62-9b09ae1bf22a", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'literature'" - ] - }, - "execution_count": 84, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj._ClassAttr__book" - ] - }, - { - "cell_type": "code", - "execution_count": 85, - "id": "e655f101-7daa-47fd-bb9b-f8699a8c7c78", - "metadata": {}, - "outputs": [], - "source": [ - "obj.print_book = lambda self: f\"{self.__book=}\"" - ] - }, - { - "cell_type": "code", - "execution_count": 87, - "id": "e066dba4-cf73-4008-92fe-aab3d96cdc23", - "metadata": {}, - "outputs": [ - { - "ename": "AttributeError", - "evalue": "'ClassAttr' object has no attribute '__book'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[87]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mobj\u001b[49m\u001b[43m.\u001b[49m\u001b[43mprint_book\u001b[49m\u001b[43m(\u001b[49m\u001b[43mobj\u001b[49m\u001b[43m)\u001b[49m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[85]\u001b[39m\u001b[32m, line 1\u001b[39m, in \u001b[36m\u001b[39m\u001b[34m(self)\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m obj.print_book = \u001b[38;5;28;01mlambda\u001b[39;00m \u001b[38;5;28mself\u001b[39m: \u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m__book\u001b[49m\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m\n", - "\u001b[31mAttributeError\u001b[39m: 'ClassAttr' object has no attribute '__book'" - ] - } - ], - "source": [ - "obj.print_book(obj)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1b113f27-a2b3-4f1b-8f9c-caa776beebca", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 83, - "id": "22481124-f655-416e-873c-41b22fa90c1f", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'val': 10,\n", - " '_protected': 'protected',\n", - " '_ClassAttr__private': 'updated priv',\n", - " '__new_private': 'qwerty',\n", - " 'color': 'green',\n", - " '_ClassAttr__private_3': 'priv3',\n", - " '_ClassAttr__book': 'literature'}" - ] - }, - "execution_count": 83, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 72, - "id": "d9bf315a-a16b-4708-8781-358e5acaed42", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "__main__.ClassAttr" - ] - }, - "execution_count": 72, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ClassAttr" - ] - }, - { - "cell_type": "code", - "execution_count": 73, - "id": "8a74fb5e-914b-4472-83d0-144121596f55", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'__module__': '__main__',\n", - " '__firstlineno__': 1,\n", - " 'name': 'cls_name',\n", - " '_ClassAttr__cls_private': 'cls_private',\n", - " '__custom_name__': 'custom_name',\n", - " '__custom_init__': ,\n", - " '__init__': ,\n", - " 'print': ,\n", - " 'print_new': ,\n", - " '__static_attributes__': ('__private', '_protected', 'val'),\n", - " '__dict__': ,\n", - " '__weakref__': ,\n", - " '__doc__': None})" - ] - }, - "execution_count": 73, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ClassAttr.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 74, - "id": "cd35402d-9842-4b34-a113-5ab1fec6787a", - "metadata": {}, - "outputs": [], - "source": [ - "obj.__dict__[\"color\"] = \"green\"" - ] - }, - { - "cell_type": "code", - "execution_count": 75, - "id": "fa2fd3be-8d5c-4800-bd5d-ced5179e6de1", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'green'" - ] - }, - "execution_count": 75, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.color" - ] - }, - { - "cell_type": "code", - "execution_count": 76, - "id": "44e04d3d-0d0c-462e-afc2-d73b822fc358", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "'mappingproxy' object does not support item assignment", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[76]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mClassAttr\u001b[49m\u001b[43m.\u001b[49m\u001b[34;43m__dict__\u001b[39;49m\u001b[43m[\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mweight\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m]\u001b[49m = \u001b[32m99\u001b[39m\n", - "\u001b[31mTypeError\u001b[39m: 'mappingproxy' object does not support item assignment" - ] - } - ], - "source": [ - "ClassAttr.__dict__[\"weight\"] = 99" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1071d8df-2782-4d29-8a38-fb44aee697a8", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a1bf9306-82b2-4894-ad86-7b1688ea47d2", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a2d4ff24-1b90-4a36-a66e-41d956921ccd", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 88, - "id": "b837fcab-ee06-43d4-88e6-3d920474a9d3", - "metadata": {}, - "outputs": [], - "source": [ - "obj = ClassAttr(10)" - ] - }, - { - "cell_type": "code", - "execution_count": 89, - "id": "b2ef022f-6de9-4395-b213-f81f1a57530c", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'val': 10, '_protected': 'protected', '_ClassAttr__private': 'private'}" - ] - }, - "execution_count": 89, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 90, - "id": "5146b8b7-7e7f-41a4-a316-1151cd55e3ca", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'cls_name'" - ] - }, - "execution_count": 90, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ClassAttr.name" - ] - }, - { - "cell_type": "code", - "execution_count": 92, - "id": "afbb28cf-5e00-4fd5-936f-35c2c8051e08", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'cls_name'" - ] - }, - "execution_count": 92, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.name" - ] - }, - { - "cell_type": "code", - "execution_count": 93, - "id": "f66c62c3-4bd8-4c44-91d4-064b19ac1b65", - "metadata": {}, - "outputs": [], - "source": [ - "obj.name = \"obj_name\"" - ] - }, - { - "cell_type": "code", - "execution_count": 94, - "id": "f09bb3d1-022f-4c27-92ce-5e8abdf2964b", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "('obj_name', 'cls_name')" - ] - }, - "execution_count": 94, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.name, ClassAttr.name" - ] - }, - { - "cell_type": "code", - "execution_count": 95, - "id": "64181baa-87d1-4a05-809f-a8ab05d6910e", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'val': 10,\n", - " '_protected': 'protected',\n", - " '_ClassAttr__private': 'private',\n", - " 'name': 'obj_name'}" - ] - }, - "execution_count": 95, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 96, - "id": "8ce8f074-9a76-41b4-9b30-5255187a32fd", - "metadata": {}, - "outputs": [], - "source": [ - "del obj.name" - ] - }, - { - "cell_type": "code", - "execution_count": 97, - "id": "2d0ec983-fee0-4009-aa0e-9f6962d4996c", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "('cls_name', 'cls_name')" - ] - }, - "execution_count": 97, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.name, ClassAttr.name" - ] - }, - { - "cell_type": "code", - "execution_count": 98, - "id": "d3c94340-19ee-4ef0-ac55-a195023b619e", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'val': 10, '_protected': 'protected', '_ClassAttr__private': 'private'}" - ] - }, - "execution_count": 98, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 99, - "id": "157979dd-26df-4e4b-b954-3e7c2426dc35", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "__main__.ClassAttr" - ] - }, - "execution_count": 99, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.__class__" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8df2fc58-10df-407c-947d-11e4e5d30d2b", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a9770f16-fa9f-424a-8fe0-6a6fc1ad8b09", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 113, - "id": "78e61da0-dc4e-42a5-bbc7-24d3992ddfd2", - "metadata": {}, - "outputs": [], - "source": [ - "class ClassAttr:\n", - " name = \"cls_name\"\n", - " __cls_private = \"cls_private\"\n", - "\n", - " @staticmethod\n", - " def stats():\n", - " return \"stats\"\n", - "\n", - " @classmethod\n", - " def update_name(cls, name):\n", - " print(f\"{cls=}\")\n", - " cls.name = name\n", - " \n", - " def __init__(self, val):\n", - " self.val = val\n", - " self._protected = \"protected\"\n", - " self.__private = \"private\"\n", - "\n", - " def print(self):\n", - " print(f\"print data: {self.val=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 114, - "id": "5c248230-7433-44e5-a8a0-dc4095eb4d0e", - "metadata": {}, - "outputs": [], - "source": [ - "obj = ClassAttr(10)" - ] - }, - { - "cell_type": "code", - "execution_count": 105, - "id": "89ddcbbc-eb30-448a-b51d-6be6ca13f4ba", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "('stats', 'stats')" - ] - }, - "execution_count": 105, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.stats(), ClassAttr.stats()" - ] - }, - { - "cell_type": "code", - "execution_count": 106, - "id": "b3afbb63-ad54-4dc3-b921-1d396d1be311", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "cls=\n" - ] - } - ], - "source": [ - "obj.update_name(\"obj_name\")" - ] - }, - { - "cell_type": "code", - "execution_count": 107, - "id": "b3028307-a07a-45b8-b48c-db635632f181", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "<__main__.ClassAttr at 0x10b7cf0e0>" - ] - }, - "execution_count": 107, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj" - ] - }, - { - "cell_type": "code", - "execution_count": 109, - "id": "0cbbc7f1-348c-42be-b671-b69bd54ac57d", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'obj_name'" - ] - }, - "execution_count": 109, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ClassAttr.name" - ] - }, - { - "cell_type": "code", - "execution_count": 110, - "id": "9d58dc6a-94ef-4ba7-9df9-7d670fc27f11", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'val': 10, '_protected': 'protected', '_ClassAttr__private': 'private'}" - ] - }, - "execution_count": 110, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 111, - "id": "f5e8db57-7a6e-4035-8972-4a26ce2af739", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "cls=\n" - ] - } - ], - "source": [ - "ClassAttr.update_name(\"v2_name\")" - ] - }, - { - "cell_type": "code", - "execution_count": 112, - "id": "a4e4d3c6-d1ed-41ca-b49b-070a8077f371", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "('v2_name', 'v2_name')" - ] - }, - "execution_count": 112, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ClassAttr.name, obj.name" - ] - }, - { - "cell_type": "code", - "execution_count": 115, - "id": "9decef45-3e4e-452b-8ea7-bc65d77d85fe", - "metadata": {}, - "outputs": [], - "source": [ - "obj = ClassAttr(10)" - ] - }, - { - "cell_type": "code", - "execution_count": 116, - "id": "510f2066-657e-4c54-8029-eece06b63fbe", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "print data: self.val=10\n" - ] - } - ], - "source": [ - "obj.print()" - ] - }, - { - "cell_type": "code", - "execution_count": 117, - "id": "80ce083c-86b7-4e35-9ef1-9e57b61eabbd", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 117, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ClassAttr.print" - ] - }, - { - "cell_type": "code", - "execution_count": 120, - "id": "a9f78f84-2bca-44a1-a537-49f23e51ce32", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - ">" - ] - }, - "execution_count": 120, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "obj.print" - ] - }, - { - "cell_type": "code", - "execution_count": 121, - "id": "5688b342-1d9e-49af-8b15-4a092191ac46", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "print data: self.val=10\n" - ] - } - ], - "source": [ - "ClassAttr.print(obj)" - ] - }, - { - "cell_type": "code", - "execution_count": 122, - "id": "8e9cfe3f-c292-4888-bb59-2d37363b9770", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "print data: self.val=99\n" - ] - } - ], - "source": [ - "class Data:\n", - " val = 99\n", - "\n", - "ClassAttr.print(Data)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "99ec91c1-b320-41dc-b70e-afb919d5a8d6", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f69d32ba-68a8-4284-9eaa-5fa327f7e198", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "54435209-a449-47cf-aad9-e9a5c17ad28d", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 118, - "id": "09da45a0-26f9-457c-9c99-085103cf251c", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - ">" - ] - }, - "execution_count": 118, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ClassAttr.update_name" - ] - }, - { - "cell_type": "code", - "execution_count": 119, - "id": "efd7b300-9cca-435b-9fe0-f3eef4a06aef", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 119, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ClassAttr.stats" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a3902a33-9cab-4f0f-8593-f523e2efc38e", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7859b2e8-22e4-4420-8170-d87ffb341ef6", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 127, - "id": "71558a57-2b0d-4971-b2a2-40e9e0f3a842", - "metadata": {}, - "outputs": [], - "source": [ - "class Num:\n", - " def __init__(self, n):\n", - " self.n = n\n", - "\n", - " def __add__(self, other):\n", - " print(f\"add num {self.n=}, {other=}\")\n", - " return self.n + other" - ] - }, - { - "cell_type": "code", - "execution_count": 128, - "id": "9972e4f7-aff8-4478-957e-5a62841a8e45", - "metadata": {}, - "outputs": [], - "source": [ - "n = Num(10)" - ] - }, - { - "cell_type": "code", - "execution_count": 129, - "id": "afdcf0cf-3538-4756-8c76-d4b8f1194795", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "add num self.n=10, other=20\n" - ] - }, - { - "data": { - "text/plain": [ - "30" - ] - }, - "execution_count": 129, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "n + 20" - ] - }, - { - "cell_type": "code", - "execution_count": 130, - "id": "e0de206b-ecab-41a6-8857-0ac24b41f8e2", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "unsupported operand type(s) for +: 'int' and 'Num'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[130]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[32;43m20\u001b[39;49m\u001b[43m \u001b[49m\u001b[43m+\u001b[49m\u001b[43m \u001b[49m\u001b[43mn\u001b[49m\n", - "\u001b[31mTypeError\u001b[39m: unsupported operand type(s) for +: 'int' and 'Num'" - ] - } - ], - "source": [ - "20 + n" - ] - }, - { - "cell_type": "code", - "execution_count": 131, - "id": "a1a147ec-a49c-4041-87bd-8819a94eea46", - "metadata": {}, - "outputs": [], - "source": [ - "class Num:\n", - " def __init__(self, n):\n", - " self.n = n\n", - "\n", - " def __add__(self, other):\n", - " print(f\"add num {self.n=}, {other=}\")\n", - " return self.n + other\n", - "\n", - " def __radd__(self, other):\n", - " print(f\"radd num {self.n=}, {other=}\")\n", - " return self.n + other" - ] - }, - { - "cell_type": "code", - "execution_count": 132, - "id": "a1495a4c-ebbc-4c4a-97d9-a2503e2a3f46", - "metadata": {}, - "outputs": [], - "source": [ - "n = Num(10)" - ] - }, - { - "cell_type": "code", - "execution_count": 136, - "id": "2c03cdd8-7086-4a35-99e7-8181b1b2fa3e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "radd num self.n=10, other=20\n" - ] - }, - { - "data": { - "text/plain": [ - "30" - ] - }, - "execution_count": 136, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "20 + n # 20.__add__(n) -> failed, n.__radd__(20)" - ] - }, - { - "cell_type": "code", - "execution_count": 135, - "id": "86235a69-cbde-41a0-a4fe-4f44143b0e7a", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "add num self.n=10, other=20\n" - ] - }, - { - "data": { - "text/plain": [ - "30" - ] - }, - "execution_count": 135, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "n + 20 # n.__add__(20)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c62b5b98-6b18-49eb-815a-e5429867aff6", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b3fef265-eac1-4d5a-a4c3-4b4c6cf0a333", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 137, - "id": "7053c4f9-8cba-4833-b445-d1f855ab5e25", - "metadata": {}, - "outputs": [], - "source": [ - "class A:\n", - " pass\n", - "\n", - "\n", - "class B(A):\n", - " pass\n", - "\n", - "\n", - "class C(A):\n", - " pass\n", - "\n", - "\n", - "class D(B, C):\n", - " pass" - ] - }, - { - "cell_type": "code", - "execution_count": 138, - "id": "a84f8484-0f34-4e0b-b4eb-069b50fc8d3d", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(__main__.D, __main__.B, __main__.C, __main__.A, object)" - ] - }, - "execution_count": 138, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "D.__mro__" - ] - }, - { - "cell_type": "code", - "execution_count": 139, - "id": "678ba437-98a3-41da-a205-7671abf8490b", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "Cannot create a consistent method resolution order (MRO) for bases A, B", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[139]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[38;5;28;43;01mclass\u001b[39;49;00m\u001b[38;5;250;43m \u001b[39;49m\u001b[34;43;01mE\u001b[39;49;00m\u001b[43m(\u001b[49m\u001b[43mA\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mB\u001b[49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m 2\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mpass\u001b[39;49;00m\n", - "\u001b[31mTypeError\u001b[39m: Cannot create a consistent method resolution order (MRO) for bases A, B" - ] - } - ], - "source": [ - "class E(A, B):\n", - " pass" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "21ebdd6d-1b95-46ea-b381-3e372394d703", - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.13.2" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/lesson-03/homework.md b/lesson-03/homework.md deleted file mode 100644 index bf58167..0000000 --- a/lesson-03/homework.md +++ /dev/null @@ -1,35 +0,0 @@ -# Домашнее задание #03 (Классы, ООП) - -### 1. Реализовать класс CustomList наследованием от list - -При этом: -- `CustomList` должен наследоваться от встроенного списка `list` для получения всех методов последнего (UserList можно, но манипулировать его data напрямую не следует); -- экземпляры `CustomList` можно складывать и вычитать друг с другом, с обычными списками и с числами: - ```py - CustomList([5, 1, 3, 7]) + CustomList([1, 2, 7]) # CustomList([6, 3, 10, 7]) - CustomList([10]) + [2, 5] # CustomList([12, 5]) - [2, 5] + CustomList([10]) # CustomList([12, 5]) - CustomList([2, 5]) + 10 # CustomList([12, 15]) - 10 + CustomList([2, 5]) # CustomList([12, 15]) - - CustomList([5, 1, 3, 7]) - CustomList([1, 2, 7]) # CustomList([4, -1, -4, 7]) - CustomList([10]) - [2, 5] # CustomList([8, -5]) - [2, 5] - CustomList([10]) # CustomList([-8, 5]) - CustomList([2, 5]) - 10 # CustomList([-8, -5]) - 10 - CustomList([2, 5]) # CustomList([8, 5]) - ``` - Возвращаться должен новый экземпляр `CustomList`, элементы которого будут результатом поэлементного сложения/вычитания элементов исходных списков. - Сложение/вычитание с числом выполняется как сложение/вычитание каждого элемента списка с данным числом; -- при сложении/вычитании списков разной длины отсутствующие элементы меньшего списка считаются нулями; -- после сложения/вычитания исходные списки не должны изменяться; -- при сравнении (`==`, `!=`, `>`, `>=`, `<`, `<=`) экземмпляров CustomList должна сравниваться сумма элементов списков (сравнение с `list` и `int` не нужно); -- должен быть переопределен `str`, чтобы выводились элементы списка и их сумма; -- можно считать элементы списка `CustomList`, `list` и другие операнды всегда всегда целыми числами. - -### 2. Тесты CustomList в отдельном модуле -Тесты должны обязательно охватывать переопределенные методы. - -### 3. Зеленый пайплайн в репе -Обязательно: тесты, покрытие, flake8, pylint. -Опционально можно добавить другие инструменты, например, mypy и black. -Покрытие тестов должно составлять не менее 90%. diff --git a/lesson-03/lesson-03.pdf b/lesson-03/lesson-03.pdf deleted file mode 100644 index 5d54c3f..0000000 Binary files a/lesson-03/lesson-03.pdf and /dev/null differ diff --git a/lesson-04/class_04.ipynb b/lesson-04/class_04.ipynb deleted file mode 100644 index f9409f7..0000000 --- a/lesson-04/class_04.ipynb +++ /dev/null @@ -1,3511 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 25, - "id": "256ce273-7d3d-478e-84e7-10f253b59777", - "metadata": {}, - "outputs": [], - "source": [ - "class Person:\n", - " def __init__(self, name, age):\n", - " self.age = age\n", - " self._name = name\n", - "\n", - " @property\n", - " def age(self):\n", - " print(f\"Person {self._age=}\")\n", - " return self._age\n", - "\n", - " @age.setter\n", - " def age(self, val):\n", - " if not (isinstance(val, int) and val >= 0):\n", - " raise ValueError(\"age must be non-negative int\")\n", - " self._age = val\n", - " print(f\"Person set {self._age=}, {val=}\")\n", - "\n", - " @property\n", - " def name(self):\n", - " print(f\"Person {self._name=}\")\n", - " return self._name\n", - "\n", - " def calc(self, val):\n", - " print(\"Person.calc\", val)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8bc1c621-9fd1-47d0-9b18-55201d747735", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "7b1215a0-4ec9-4fb6-9d2e-46c947d9f948", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person set self._age=99, val=99\n" - ] - } - ], - "source": [ - "steve = Person(\"steve\", 99)" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "425d2485-fc48-434f-93e2-8336b640cf39", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'_age': 99, '_name': 'steve'}" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "3de324e0-a29a-4357-a383-707941a66f46", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'__module__': '__main__',\n", - " '__firstlineno__': 1,\n", - " '__init__': ,\n", - " 'age': ,\n", - " 'name': ,\n", - " '__static_attributes__': ('_age', '_name', 'age'),\n", - " '__dict__': ,\n", - " '__weakref__': ,\n", - " '__doc__': None})" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Person.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "e4b299db-779e-4b40-9a48-4e08b4f13b13", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person self._age=99\n", - "Person self._name='steve'\n" - ] - }, - { - "data": { - "text/plain": [ - "(99, 'steve')" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.age, steve.name" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "dd9f788d-d283-405f-bd6b-db81d81af8e5", - "metadata": {}, - "outputs": [ - { - "ename": "AttributeError", - "evalue": "property 'name' of 'Person' object has no setter", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[6]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43msteve\u001b[49m\u001b[43m.\u001b[49m\u001b[43mname\u001b[49m = \u001b[33m\"\u001b[39m\u001b[33mupdate_steve\u001b[39m\u001b[33m\"\u001b[39m\n", - "\u001b[31mAttributeError\u001b[39m: property 'name' of 'Person' object has no setter" - ] - } - ], - "source": [ - "steve.name = \"update_steve\"" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "5fd914a0-1b04-4abf-92ea-5afef490cedf", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person self._age=99\n", - "Person self._name='steve'\n" - ] - }, - { - "data": { - "text/plain": [ - "(99, 'steve')" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.age, steve.name" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "f1784d13-668e-4279-bab4-04f91175f34d", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person set self._age=88, val=88\n" - ] - } - ], - "source": [ - "steve.age = 88" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "f3a54653-284d-433e-a2be-7a0c8cc12e53", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person self._age=99\n", - "Person self._name='steve'\n" - ] - }, - { - "data": { - "text/plain": [ - "(99, 'steve')" - ] - }, - "execution_count": 12, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.age, steve.name" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5d57c7bb-2b64-4d58-a677-9f2c54b6a6ef", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "b3672e7c-76e8-4ef9-bbda-66acc8b81294", - "metadata": {}, - "outputs": [ - { - "ename": "ValueError", - "evalue": "age must be non-negative int", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mValueError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[13]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43msteve\u001b[49m\u001b[43m.\u001b[49m\u001b[43mage\u001b[49m = \u001b[33m\"\u001b[39m\u001b[33mage\u001b[39m\u001b[33m\"\u001b[39m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[10]\u001b[39m\u001b[32m, line 14\u001b[39m, in \u001b[36mPerson.age\u001b[39m\u001b[34m(self, val)\u001b[39m\n\u001b[32m 11\u001b[39m \u001b[38;5;129m@age\u001b[39m.setter\n\u001b[32m 12\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mage\u001b[39m(\u001b[38;5;28mself\u001b[39m, val):\n\u001b[32m 13\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28misinstance\u001b[39m(val, \u001b[38;5;28mint\u001b[39m) \u001b[38;5;129;01mand\u001b[39;00m val >= \u001b[32m0\u001b[39m):\n\u001b[32m---> \u001b[39m\u001b[32m14\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[33m\"\u001b[39m\u001b[33mage must be non-negative int\u001b[39m\u001b[33m\"\u001b[39m)\n\u001b[32m 15\u001b[39m \u001b[38;5;28mself\u001b[39m._age = val\n\u001b[32m 16\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mPerson set \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m._age\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mval\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", - "\u001b[31mValueError\u001b[39m: age must be non-negative int" - ] - } - ], - "source": [ - "steve.age = \"age\"" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "d5366429-43c6-4c54-a276-84ef50e91a02", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person self._age=99\n", - "Person self._name='steve'\n" - ] - }, - { - "data": { - "text/plain": [ - "(99, 'steve')" - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.age, steve.name" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "249d5178-191b-4176-83a2-fbf962cbf261", - "metadata": {}, - "outputs": [ - { - "ename": "ValueError", - "evalue": "age must be non-negative int", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mValueError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[16]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m pers = \u001b[43mPerson\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43msteve\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m-\u001b[49m\u001b[32;43m99\u001b[39;49m\u001b[43m)\u001b[49m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[10]\u001b[39m\u001b[32m, line 3\u001b[39m, in \u001b[36mPerson.__init__\u001b[39m\u001b[34m(self, name, age)\u001b[39m\n\u001b[32m 2\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34m__init__\u001b[39m(\u001b[38;5;28mself\u001b[39m, name, age):\n\u001b[32m----> \u001b[39m\u001b[32m3\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mage\u001b[49m = age\n\u001b[32m 4\u001b[39m \u001b[38;5;28mself\u001b[39m._name = name\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[10]\u001b[39m\u001b[32m, line 14\u001b[39m, in \u001b[36mPerson.age\u001b[39m\u001b[34m(self, val)\u001b[39m\n\u001b[32m 11\u001b[39m \u001b[38;5;129m@age\u001b[39m.setter\n\u001b[32m 12\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mage\u001b[39m(\u001b[38;5;28mself\u001b[39m, val):\n\u001b[32m 13\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28misinstance\u001b[39m(val, \u001b[38;5;28mint\u001b[39m) \u001b[38;5;129;01mand\u001b[39;00m val >= \u001b[32m0\u001b[39m):\n\u001b[32m---> \u001b[39m\u001b[32m14\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[33m\"\u001b[39m\u001b[33mage must be non-negative int\u001b[39m\u001b[33m\"\u001b[39m)\n\u001b[32m 15\u001b[39m \u001b[38;5;28mself\u001b[39m._age = val\n\u001b[32m 16\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mPerson set \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m._age\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mval\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", - "\u001b[31mValueError\u001b[39m: age must be non-negative int" - ] - } - ], - "source": [ - "pers = Person(\"steve\", -99)" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "ec3bec40-51fc-4e96-addb-aad84056e130", - "metadata": {}, - "outputs": [ - { - "ename": "NameError", - "evalue": "name 'pers' is not defined", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mNameError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[17]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mpers\u001b[49m\n", - "\u001b[31mNameError\u001b[39m: name 'pers' is not defined" - ] - } - ], - "source": [ - "pers" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "06733c6f-7911-4837-be1c-0da2ad68dca8", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c615ac27-1c81-475c-bd8c-bbd989ef1364", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "4aabfd6d-b5ca-49ff-8482-ef7bd708e444", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'_age': 99, '_name': 'steve'}" - ] - }, - "execution_count": 19, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "6a7cd7d4-e731-498c-a051-8c68a712b68b", - "metadata": {}, - "outputs": [], - "source": [ - "steve.__dict__[\"_age\"] = \"age\"\n", - "steve.__dict__[\"_name\"] = \"updated_steve\"" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "ea949e82-fec3-487d-b64b-ffc273c71064", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person self._age='age'\n", - "Person self._name='updated_steve'\n" - ] - }, - { - "data": { - "text/plain": [ - "('age', 'updated_steve')" - ] - }, - "execution_count": 21, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.age, steve.name" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9b635bf8-aeda-48dc-8a6b-55909320b9a5", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "09038fae-e157-4cfb-9d1f-b6554da3b5ed", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "414869e6-6d0b-46d0-a39e-1bbf20161730", - "metadata": {}, - "outputs": [], - "source": [ - "steve.__dict__[\"age\"] = \"modified_age\"\n", - "steve.__dict__[\"name\"] = \"modified_name\"" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "0da6f533-380d-4f61-b1f9-c1eeeb05439b", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person self._age=99\n", - "Person self._name='steve'\n" - ] - }, - { - "data": { - "text/plain": [ - "(99, 'steve')" - ] - }, - "execution_count": 29, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.age, steve.name" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "054dc5c1-6a7e-4795-994d-0bdb28a3f73b", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'_age': 99, '_name': 'steve', 'age': 'modified_age', 'name': 'modified_name'}" - ] - }, - "execution_count": 30, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "2416c3e6-2c68-4234-97b6-9cfd686ee780", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person.calc 25\n" - ] - } - ], - "source": [ - "steve.calc(25)" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "f11d2da7-a14b-430c-9fcc-562e3b5e8b16", - "metadata": {}, - "outputs": [], - "source": [ - "steve.__dict__[\"calc\"] = \"new_calc\"" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "249bd29f-cfae-4950-bdbd-403191630d0d", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'_age': 99,\n", - " '_name': 'steve',\n", - " 'age': 'modified_age',\n", - " 'name': 'modified_name',\n", - " 'calc': 'new_calc'}" - ] - }, - "execution_count": 33, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "46dd0721-fb63-4f39-a061-521371029953", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'new_calc'" - ] - }, - "execution_count": 36, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.calc" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "3ffb78e4-b608-4106-8e17-407ae1cc6130", - "metadata": {}, - "outputs": [], - "source": [ - "del steve.calc" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "id": "fcd8e419-f154-4b52-86dd-362ebaeea3e8", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person.calc 25\n" - ] - } - ], - "source": [ - "steve.calc(25)" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "77f4534d-2579-4c21-a90b-667e39381d36", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'_age': 99, '_name': 'steve', 'age': 'modified_age', 'name': 'modified_name'}" - ] - }, - "execution_count": 39, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4d867f13-a880-4137-8040-402e349098a8", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "60238014-21cf-44ad-a823-227ee4aad18d", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9f5f66b6-3789-4988-8693-f4d33885c5b4", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 40, - "id": "60fbb230-0446-4fd6-b909-31fac8a670e8", - "metadata": {}, - "outputs": [], - "source": [ - "def make_hash_from_password(password):\n", - " return hash(password)\n", - "\n", - "\n", - "class User:\n", - " def __init__(self, login, password):\n", - " self.login = login\n", - " self.password_hash = None\n", - " self.password = password\n", - "\n", - " @property\n", - " def login(self):\n", - " return self.__system_id, self.__name\n", - "\n", - " @login.setter\n", - " def login(self, val):\n", - " self.__system_id, self.__name = val\n", - " \n", - " print(f\"{self.__system_id=}, {self.__name=}\")\n", - "\n", - " @property\n", - " def password(self):\n", - " raise AttributeError(\"Password is write-only\")\n", - "\n", - " @password.setter\n", - " def password(self, plaintext):\n", - " self.password_hash = make_hash_from_password(plaintext)\n" - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "id": "e3833872-0279-4a97-ae54-792802583334", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "self.__system_id=999, self.__name='steve'\n" - ] - } - ], - "source": [ - "steve = User((999, \"steve\"), \"12345\")" - ] - }, - { - "cell_type": "code", - "execution_count": 43, - "id": "91895395-3709-4325-a197-dcc848963458", - "metadata": {}, - "outputs": [ - { - "ename": "ValueError", - "evalue": "too many values to unpack (expected 2)", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mValueError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[43]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43msteve\u001b[49m\u001b[43m.\u001b[49m\u001b[43mlogin\u001b[49m = \u001b[33m\"\u001b[39m\u001b[33mdwkjdkwj\u001b[39m\u001b[33m\"\u001b[39m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[40]\u001b[39m\u001b[32m, line 17\u001b[39m, in \u001b[36mUser.login\u001b[39m\u001b[34m(self, val)\u001b[39m\n\u001b[32m 15\u001b[39m \u001b[38;5;129m@login\u001b[39m.setter\n\u001b[32m 16\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mlogin\u001b[39m(\u001b[38;5;28mself\u001b[39m, val):\n\u001b[32m---> \u001b[39m\u001b[32m17\u001b[39m \u001b[38;5;28mself\u001b[39m.__system_id, \u001b[38;5;28mself\u001b[39m.__name = val\n\u001b[32m 19\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m.__system_id\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m.__name\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n", - "\u001b[31mValueError\u001b[39m: too many values to unpack (expected 2)" - ] - } - ], - "source": [ - "steve.login = \"dwkjdkwj\"" - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "id": "9d76b231-d567-4813-9a05-af85d20509a8", - "metadata": {}, - "outputs": [ - { - "ename": "AttributeError", - "evalue": "Password is write-only", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[44]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43msteve\u001b[49m\u001b[43m.\u001b[49m\u001b[43mpassword\u001b[49m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[40]\u001b[39m\u001b[32m, line 23\u001b[39m, in \u001b[36mUser.password\u001b[39m\u001b[34m(self)\u001b[39m\n\u001b[32m 21\u001b[39m \u001b[38;5;129m@property\u001b[39m\n\u001b[32m 22\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mpassword\u001b[39m(\u001b[38;5;28mself\u001b[39m):\n\u001b[32m---> \u001b[39m\u001b[32m23\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mAttributeError\u001b[39;00m(\u001b[33m\"\u001b[39m\u001b[33mPassword is write-only\u001b[39m\u001b[33m\"\u001b[39m)\n", - "\u001b[31mAttributeError\u001b[39m: Password is write-only" - ] - } - ], - "source": [ - "steve.password" - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "id": "c81304ce-e2f5-45f9-b159-6dcd97da0a67", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'_User__system_id': 999,\n", - " '_User__name': 'steve',\n", - " 'password_hash': 3181687054709848191}" - ] - }, - "execution_count": 45, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c5eb7f53-1168-4d2f-a31e-f6c7251ed601", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 46, - "id": "09c4ad8c-429b-4054-b018-e4da5de1fa5e", - "metadata": {}, - "outputs": [], - "source": [ - "steve.password = \"123456\"" - ] - }, - { - "cell_type": "code", - "execution_count": 47, - "id": "b467b36e-87e3-4efe-a3ea-a8d7cd04b906", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'_User__system_id': 999,\n", - " '_User__name': 'steve',\n", - " 'password_hash': -3625561019045039867}" - ] - }, - "execution_count": 47, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a7815886-1f9d-4586-bdc9-34251661a723", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d9d92cd6-f37d-4912-a6bb-b7ad6d96cfba", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5e32e4c6-c931-47ff-a941-0c22b6ee45d7", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 59, - "id": "c0bd2f00-f034-48e5-b6d8-2d4cb8fe3ff7", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__setattr__ name='val', val=42\n" - ] - } - ], - "source": [ - "class AttrAccess:\n", - " name = \"cls_attribut_access\"\n", - "\n", - " def __init__(self, val):\n", - " self.val = val\n", - "\n", - " def __getattribute__(self, name):\n", - " print(f\"__getattribute__ {name=}\")\n", - " \n", - " return super().__getattribute__(name)\n", - " \n", - " def __setattr__(self, name, val):\n", - " print(f\"__setattr__ {name=}, {val=}\")\n", - " \n", - " return super().__setattr__(name, val)\n", - "\n", - " def __delattr__(self, name):\n", - " print(f\"__delattr__ {name=}\")\n", - " \n", - " return super().__delattr__(name)\n", - "\n", - " def calc(self, val):\n", - " print(f\"calc\", val)\n", - "\n", - " \n", - "attr = AttrAccess(42)" - ] - }, - { - "cell_type": "code", - "execution_count": 51, - "id": "be7fba9e-e6f7-4cc1-a32d-fdcd26eb1a34", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='val'\n" - ] - }, - { - "data": { - "text/plain": [ - "42" - ] - }, - "execution_count": 51, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "attr.val" - ] - }, - { - "cell_type": "code", - "execution_count": 53, - "id": "805947b8-7ad3-4ecf-a9ef-69a884397f48", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='calc'\n", - "calc 99\n" - ] - } - ], - "source": [ - "attr.calc(99)" - ] - }, - { - "cell_type": "code", - "execution_count": 54, - "id": "d2758957-8325-4fae-b1f3-59001d43d749", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='name'\n" - ] - }, - { - "data": { - "text/plain": [ - "'cls_attribut_access'" - ] - }, - "execution_count": 54, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "attr.name" - ] - }, - { - "cell_type": "code", - "execution_count": 55, - "id": "1a5ba2c1-dd07-47a8-890d-e9667658127e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='fake'\n" - ] - }, - { - "ename": "AttributeError", - "evalue": "'AttrAccess' object has no attribute 'fake'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[55]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mattr\u001b[49m\u001b[43m.\u001b[49m\u001b[43mfake\u001b[49m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[50]\u001b[39m\u001b[32m, line 10\u001b[39m, in \u001b[36mAttrAccess.__getattribute__\u001b[39m\u001b[34m(self, name)\u001b[39m\n\u001b[32m 7\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34m__getattribute__\u001b[39m(\u001b[38;5;28mself\u001b[39m, name):\n\u001b[32m 8\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33m__getattribute__ \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mname\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m---> \u001b[39m\u001b[32m10\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m.\u001b[49m\u001b[34;43m__getattribute__\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mname\u001b[49m\u001b[43m)\u001b[49m\n", - "\u001b[31mAttributeError\u001b[39m: 'AttrAccess' object has no attribute 'fake'" - ] - } - ], - "source": [ - "attr.fake" - ] - }, - { - "cell_type": "code", - "execution_count": 56, - "id": "7fb81b2c-b508-4f7a-8516-89e67b7152a9", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__setattr__ name='fake', val='fake_val'\n" - ] - } - ], - "source": [ - "attr.fake = \"fake_val\"" - ] - }, - { - "cell_type": "code", - "execution_count": 57, - "id": "3c3551f0-8f1d-41cd-ae61-9e35a3e513b5", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='fake'\n" - ] - }, - { - "data": { - "text/plain": [ - "'fake_val'" - ] - }, - "execution_count": 57, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "attr.fake" - ] - }, - { - "cell_type": "code", - "execution_count": 58, - "id": "d0189a90-f7bb-4290-85b7-80fe2cf0d6c1", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__delattr__ name='fake'\n" - ] - } - ], - "source": [ - "del attr.fake" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "23cbfaa7-7c0a-4fe7-ae18-1021a2130b36", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "beff029f-737d-4705-9b4b-d408b5329fd8", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 66, - "id": "65fc131d-5bc2-429a-b4cc-c913c1f86a19", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__setattr__ name='val', val=42\n" - ] - } - ], - "source": [ - "class AttrAccess:\n", - " name = \"cls_attribut_access\"\n", - "\n", - " def __init__(self, val):\n", - " self.val = val\n", - "\n", - " def __getattr__(self, name):\n", - " print(f\"__getatt__ {name=}\")\n", - " \n", - " raise AttributeError(f\"attr {name} does not exist\")\n", - "\n", - " def __getattribute__(self, name):\n", - " print(f\"__getattribute__ {name=}\")\n", - " \n", - " return super().__getattribute__(name)\n", - " \n", - " def __setattr__(self, name, val):\n", - " print(f\"__setattr__ {name=}, {val=}\")\n", - " \n", - " return super().__setattr__(name, val)\n", - "\n", - " def __delattr__(self, name):\n", - " print(f\"__delattr__ {name=}\")\n", - " \n", - " return super().__delattr__(name)\n", - "\n", - " def calc(self, val):\n", - " print(f\"calc\", val)\n", - "\n", - " \n", - "attr = AttrAccess(42)" - ] - }, - { - "cell_type": "code", - "execution_count": 63, - "id": "5cb8bede-560c-43e0-a253-b8318d05d375", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='fake'\n", - "__getatt__ name='fake'\n" - ] - }, - { - "data": { - "text/plain": [ - "'none'" - ] - }, - "execution_count": 63, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "attr.fake" - ] - }, - { - "cell_type": "code", - "execution_count": 64, - "id": "1a7a9adf-fe44-44a7-8955-fe8eca41ec59", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='__dict__'\n" - ] - }, - { - "data": { - "text/plain": [ - "{'val': 42}" - ] - }, - "execution_count": 64, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "attr.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 67, - "id": "9940445a-8b70-42dc-8a1f-04f1dd86c8fd", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='fake'\n", - "__getatt__ name='fake'\n" - ] - }, - { - "ename": "AttributeError", - "evalue": "attr fake does not exist", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[67]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mattr\u001b[49m\u001b[43m.\u001b[49m\u001b[43mfake\u001b[49m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[66]\u001b[39m\u001b[32m, line 10\u001b[39m, in \u001b[36mAttrAccess.__getattr__\u001b[39m\u001b[34m(self, name)\u001b[39m\n\u001b[32m 7\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34m__getattr__\u001b[39m(\u001b[38;5;28mself\u001b[39m, name):\n\u001b[32m 8\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33m__getatt__ \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mname\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m---> \u001b[39m\u001b[32m10\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mAttributeError\u001b[39;00m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mattr \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mname\u001b[38;5;132;01m}\u001b[39;00m\u001b[33m does not exist\u001b[39m\u001b[33m\"\u001b[39m)\n", - "\u001b[31mAttributeError\u001b[39m: attr fake does not exist" - ] - } - ], - "source": [ - "attr.fake" - ] - }, - { - "cell_type": "code", - "execution_count": 71, - "id": "a66c4522-01f4-47cf-b460-613e90a035fe", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='val'\n" - ] - }, - { - "data": { - "text/plain": [ - "42" - ] - }, - "execution_count": 71, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "attr.val" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2ccf2169-4355-427b-9fd9-9642b0db35c6", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fb9ef23b-b3d4-4ec0-a007-df4871bbf78c", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 74, - "id": "0a35ee2d-d693-4843-bf77-8fbc3f49a605", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='val'\n", - "__getattribute__ name='val'\n" - ] - }, - { - "data": { - "text/plain": [ - "(True, 42)" - ] - }, - "execution_count": 74, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "hasattr(attr, \"val\"), getattr(attr, \"val\")" - ] - }, - { - "cell_type": "code", - "execution_count": 73, - "id": "605fa7b7-b90d-4a7c-adf4-60a2eee3dc6e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='__dict__'\n" - ] - }, - { - "data": { - "text/plain": [ - "{'val': 42}" - ] - }, - "execution_count": 73, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "attr.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 75, - "id": "dce2bb13-4715-4c63-95f2-0a6fcc2a0bd8", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='val1223'\n", - "__getatt__ name='val1223'\n" - ] - }, - { - "data": { - "text/plain": [ - "'default'" - ] - }, - "execution_count": 75, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "getattr(attr, \"val1223\", \"default\")" - ] - }, - { - "cell_type": "code", - "execution_count": 76, - "id": "6abeb37e-218a-47e9-b190-a5597cf86e95", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='val1223'\n", - "__getatt__ name='val1223'\n", - "default\n" - ] - } - ], - "source": [ - "try:\n", - " val = getattr(attr, \"val1223\")\n", - "except AttributeError:\n", - " val = \"default\"\n", - "\n", - "print(val)" - ] - }, - { - "cell_type": "code", - "execution_count": 77, - "id": "4cb99229-896a-41df-8c92-1061bc61450c", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='val'\n", - "42\n" - ] - } - ], - "source": [ - "try:\n", - " val = getattr(attr, \"val\")\n", - "except AttributeError:\n", - " val = \"default\"\n", - "\n", - "print(val)" - ] - }, - { - "cell_type": "code", - "execution_count": 78, - "id": "e6f30664-a1f6-449b-bf99-da2de07226f6", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__setattr__ name='fake', val='fake_val'\n" - ] - } - ], - "source": [ - "setattr(attr, \"fake\", \"fake_val\")" - ] - }, - { - "cell_type": "code", - "execution_count": 79, - "id": "f8c00cbc-4073-4a28-84fe-56cb5add6afe", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='fake'\n" - ] - }, - { - "data": { - "text/plain": [ - "'fake_val'" - ] - }, - "execution_count": 79, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "attr.fake" - ] - }, - { - "cell_type": "code", - "execution_count": 80, - "id": "e6f7de64-0017-41f1-8f76-7eaa23a1c1ea", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='fake'\n" - ] - }, - { - "data": { - "text/plain": [ - "'fake_val'" - ] - }, - "execution_count": 80, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "getattr(attr, \"fake\")" - ] - }, - { - "cell_type": "code", - "execution_count": 81, - "id": "28c64e5e-e2f6-41d3-9cab-fb139d40cfc6", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__delattr__ name='fake'\n" - ] - } - ], - "source": [ - "delattr(attr, \"fake\")" - ] - }, - { - "cell_type": "code", - "execution_count": 84, - "id": "11040922-9cce-4dbe-97c3-1d2c8379706d", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__delattr__ name='fake'\n" - ] - }, - { - "ename": "AttributeError", - "evalue": "'AttrAccess' object has no attribute 'fake'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[84]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[38;5;28;43mdelattr\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mattr\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mfake\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[66]\u001b[39m\u001b[32m, line 25\u001b[39m, in \u001b[36mAttrAccess.__delattr__\u001b[39m\u001b[34m(self, name)\u001b[39m\n\u001b[32m 22\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34m__delattr__\u001b[39m(\u001b[38;5;28mself\u001b[39m, name):\n\u001b[32m 23\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33m__delattr__ \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mname\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m---> \u001b[39m\u001b[32m25\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m.\u001b[49m\u001b[34;43m__delattr__\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mname\u001b[49m\u001b[43m)\u001b[49m\n", - "\u001b[31mAttributeError\u001b[39m: 'AttrAccess' object has no attribute 'fake'" - ] - } - ], - "source": [ - "delattr(attr, \"fake\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "eae40f03-162d-4173-beb6-d875a880cd90", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "221b514d-0ce0-40d6-a64e-8cf9b18fcbcd", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 86, - "id": "e701b77e-78e3-44f2-a94f-7811f843291e", - "metadata": {}, - "outputs": [], - "source": [ - "class PersonTable:\n", - " \n", - " def __init__(self, age):\n", - " self.age = age\n", - "\n", - " def calc(self):\n", - " print(\"Pers.calc\")\n", - " return 123\n", - "\n", - " def __call__(self, data):\n", - " print(\"Pers call\", data)\n", - " return 123\n", - "\n", - " def __del__(self):\n", - " print(\"Pers.__del__\")\n", - "\n", - "\n", - "pers = PersonTable(99)" - ] - }, - { - "cell_type": "code", - "execution_count": 87, - "id": "46ddc89a-d952-4c26-aab3-c1bf35845ff4", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'age': 99}" - ] - }, - "execution_count": 87, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 88, - "id": "a24d82be-f6d6-4d3a-b1d9-9e94f7295ea1", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "99" - ] - }, - "execution_count": 88, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.age" - ] - }, - { - "cell_type": "code", - "execution_count": 89, - "id": "ea534e5c-bb75-42ea-896c-6d4e6f6edf6e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Pers.calc\n" - ] - }, - { - "data": { - "text/plain": [ - "123" - ] - }, - "execution_count": 89, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.calc()" - ] - }, - { - "cell_type": "code", - "execution_count": 90, - "id": "75015d28-c5d6-44ae-b3b1-cc1fc3771f3e", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - ">" - ] - }, - "execution_count": 90, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.calc" - ] - }, - { - "cell_type": "code", - "execution_count": 94, - "id": "b4458d36-498f-4254-86c5-d9dd718cc47c", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Pers.calc\n" - ] - }, - { - "data": { - "text/plain": [ - "123" - ] - }, - "execution_count": 94, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.calc.__func__({})" - ] - }, - { - "cell_type": "code", - "execution_count": 95, - "id": "5a5f1b9f-3377-4362-bdab-d84437ee0347", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "<__main__.PersonTable at 0x10b7512b0>" - ] - }, - "execution_count": 95, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.calc.__self__" - ] - }, - { - "cell_type": "code", - "execution_count": 96, - "id": "0cd98941-29df-4d09-95f8-c2ce55586f46", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "<__main__.PersonTable at 0x10b7512b0>" - ] - }, - "execution_count": 96, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers" - ] - }, - { - "cell_type": "code", - "execution_count": 97, - "id": "9ef33810-0bbe-4ea5-a75d-d982588c84be", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 97, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.calc.__call__" - ] - }, - { - "cell_type": "code", - "execution_count": 98, - "id": "e6648d77-2be6-42fa-b161-3d5cb711dc73", - "metadata": {}, - "outputs": [ - { - "ename": "AttributeError", - "evalue": "'int' object has no attribute '__call__'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[98]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mpers\u001b[49m\u001b[43m.\u001b[49m\u001b[43mage\u001b[49m\u001b[43m.\u001b[49m\u001b[34;43m__call__\u001b[39;49m\n", - "\u001b[31mAttributeError\u001b[39m: 'int' object has no attribute '__call__'" - ] - } - ], - "source": [ - "pers.age.__call__" - ] - }, - { - "cell_type": "code", - "execution_count": 99, - "id": "8a2dbba8-766c-403e-96bb-f27ed8ee10e7", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Pers.calc\n" - ] - }, - { - "data": { - "text/plain": [ - "123" - ] - }, - "execution_count": 99, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.calc()" - ] - }, - { - "cell_type": "code", - "execution_count": 101, - "id": "ffa8a88d-82bc-47fe-8d13-0642f728dc97", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Pers call [1, 2]\n" - ] - }, - { - "data": { - "text/plain": [ - "123" - ] - }, - "execution_count": 101, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers([1, 2])" - ] - }, - { - "cell_type": "code", - "execution_count": 102, - "id": "f9b6f262-bd57-4188-b3c8-aae75faa1483", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - ">" - ] - }, - "execution_count": 102, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.__call__" - ] - }, - { - "cell_type": "code", - "execution_count": 103, - "id": "86d7ef76-36f8-40d7-9095-f6e52c4c6c10", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "__getattribute__ name='__call__'\n", - "__getatt__ name='__call__'\n" - ] - }, - { - "ename": "AttributeError", - "evalue": "attr __call__ does not exist", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[103]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mattr\u001b[49m\u001b[43m.\u001b[49m\u001b[34;43m__call__\u001b[39;49m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[66]\u001b[39m\u001b[32m, line 10\u001b[39m, in \u001b[36mAttrAccess.__getattr__\u001b[39m\u001b[34m(self, name)\u001b[39m\n\u001b[32m 7\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34m__getattr__\u001b[39m(\u001b[38;5;28mself\u001b[39m, name):\n\u001b[32m 8\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33m__getatt__ \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mname\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m---> \u001b[39m\u001b[32m10\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mAttributeError\u001b[39;00m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mattr \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mname\u001b[38;5;132;01m}\u001b[39;00m\u001b[33m does not exist\u001b[39m\u001b[33m\"\u001b[39m)\n", - "\u001b[31mAttributeError\u001b[39m: attr __call__ does not exist" - ] - } - ], - "source": [ - "attr.__call__" - ] - }, - { - "cell_type": "code", - "execution_count": 105, - "id": "1a570d4c-57a9-4c1c-9882-33f37a149028", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - } - ], - "source": [ - "def fn(): pass\n", - "\n", - "print(fn.__call__)" - ] - }, - { - "cell_type": "code", - "execution_count": 106, - "id": "0f641b15-645a-46c5-a815-79c7022a4e5d", - "metadata": {}, - "outputs": [], - "source": [ - "del pers" - ] - }, - { - "cell_type": "code", - "execution_count": 112, - "id": "8b01a8a0-ee3a-4879-9509-d67c28ce3075", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Pers.__del__\n", - "Pers.__del__\n" - ] - } - ], - "source": [ - "pers = PersonTable(99)\n", - "other = pers\n", - "\n", - "del pers\n", - "del other" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "deeb4e3c-27f3-4d2c-bfa9-b3b6b50b154e", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e0821595-6493-4a6d-9fdc-aba218e05d30", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "79e08de6-f3e0-4a9e-b71d-6dbabccf8069", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 113, - "id": "363149af-c8cb-458e-b7dc-9f18dfb4a553", - "metadata": {}, - "outputs": [], - "source": [ - "class Person:\n", - " def __init__(self, name, login, system_id):\n", - " self.name = name\n", - " self._login = login\n", - " self.__system_id = system_id\n", - "\n", - " def print_info(self):\n", - " print(f\"Person: {self.name=}, {self._login=}, {self.__system_id=}\")" - ] - }, - { - "cell_type": "code", - "execution_count": 114, - "id": "7f175676-7acf-4e4d-83dc-f96030885993", - "metadata": {}, - "outputs": [], - "source": [ - "pers = Person(\"Steven\", \"steve\", 123)" - ] - }, - { - "cell_type": "code", - "execution_count": 115, - "id": "2f7b52a3-89c0-47da-8ad8-ecdc04a060c8", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person: self.name='Steven', self._login='steve', self.__system_id=123\n" - ] - } - ], - "source": [ - "pers.print_info()" - ] - }, - { - "cell_type": "code", - "execution_count": 116, - "id": "bbabc768-ac22-4751-afaa-5da8b65abd7d", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'name': 'Steven', '_login': 'steve', '_Person__system_id': 123}" - ] - }, - "execution_count": 116, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cb7b5731-c0eb-4646-8bcc-32bcc1eaf2fa", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "91ca949a-1b2a-499f-a8d6-772ca2854ea5", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 118, - "id": "278d089a-24aa-4e26-8d27-3428a0a752a1", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Student.__init__\n", - "Person.__init__\n", - "Person.print_info: self.name='Steven', self._login='steve', self.__system_id=123\n" - ] - } - ], - "source": [ - "class Person:\n", - " def __init__(self, name, login, system_id):\n", - " print(\"Person.__init__\")\n", - " self.name = name\n", - " self._login = login\n", - " self.__system_id = system_id\n", - "\n", - " def print_info(self):\n", - " print(f\"Person.print_info: {self.name=}, {self._login=}, {self.__system_id=}\")\n", - "\n", - "\n", - "class Student(Person):\n", - " def __init__(self, school, *args, **kwargs):\n", - " print(\"Student.__init__\")\n", - " super().__init__(*args, **kwargs)\n", - "\n", - " self.school = school\n", - "\n", - "\n", - "steve = Student(\"hse\", \"Steven\", \"steve\", 123)\n", - "steve.print_info()" - ] - }, - { - "cell_type": "code", - "execution_count": 119, - "id": "4ceab654-5f51-466f-9123-21cf6c990ad4", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - ">" - ] - }, - "execution_count": 119, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.print_info" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "48cebaed-bc29-43dd-90bc-b1f0b2ed36c7", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "461a5675-7b9b-464d-b411-5bc2611b8325", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 120, - "id": "65d26aa5-7f5b-4728-81b6-e4a6217558fa", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Student.__init__\n", - "Person.__init__\n", - "Student.print_info: self.school='hse'\n", - "Person.print_info: self.name='Steven', self._login='steve', self.__system_id=123\n" - ] - } - ], - "source": [ - "class Person:\n", - " def __init__(self, name, login, system_id):\n", - " print(\"Person.__init__\")\n", - " self.name = name\n", - " self._login = login\n", - " self.__system_id = system_id\n", - "\n", - " def print_info(self):\n", - " print(f\"Person.print_info: {self.name=}, {self._login=}, {self.__system_id=}\")\n", - "\n", - "\n", - "class Student(Person):\n", - " def __init__(self, school, *args, **kwargs):\n", - " print(\"Student.__init__\")\n", - " super().__init__(*args, **kwargs)\n", - "\n", - " self.school = school\n", - "\n", - " def print_info(self):\n", - " print(f\"Student.print_info: {self.school=}\")\n", - " super().print_info()\n", - "\n", - "\n", - "steve = Student(\"hse\", \"Steven\", \"steve\", 123)\n", - "steve.print_info()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ab9fd285-e2ee-4444-a7a3-72d43ff7e1a0", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 123, - "id": "82351f19-15dc-4c74-b342-83315151b6e9", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Student.__init__\n", - "Person.__init__\n", - "{'name': 'Steven', '_login': 'steve', '_Person__system_id': 123, 'school': 'hse'}\n" - ] - }, - { - "ename": "AttributeError", - "evalue": "'Student' object has no attribute '_Student__system_id'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[123]\u001b[39m\u001b[32m, line 29\u001b[39m\n\u001b[32m 27\u001b[39m steve = Student(\u001b[33m\"\u001b[39m\u001b[33mhse\u001b[39m\u001b[33m\"\u001b[39m, \u001b[33m\"\u001b[39m\u001b[33mSteven\u001b[39m\u001b[33m\"\u001b[39m, \u001b[33m\"\u001b[39m\u001b[33msteve\u001b[39m\u001b[33m\"\u001b[39m, \u001b[32m123\u001b[39m)\n\u001b[32m 28\u001b[39m \u001b[38;5;28mprint\u001b[39m(steve.\u001b[34m__dict__\u001b[39m)\n\u001b[32m---> \u001b[39m\u001b[32m29\u001b[39m \u001b[43msteve\u001b[49m\u001b[43m.\u001b[49m\u001b[43mprint_info\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[123]\u001b[39m\u001b[32m, line 23\u001b[39m, in \u001b[36mStudent.print_info\u001b[39m\u001b[34m(self)\u001b[39m\n\u001b[32m 19\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mprint_info\u001b[39m(\u001b[38;5;28mself\u001b[39m):\n\u001b[32m 20\u001b[39m \u001b[38;5;28mprint\u001b[39m(\n\u001b[32m 21\u001b[39m \u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mStudent.print_info: \u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m 22\u001b[39m \u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m.school\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m.name\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m---> \u001b[39m\u001b[32m23\u001b[39m \u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mself\u001b[39m._login\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m__system_id\u001b[49m\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m\n\u001b[32m 24\u001b[39m )\n", - "\u001b[31mAttributeError\u001b[39m: 'Student' object has no attribute '_Student__system_id'" - ] - } - ], - "source": [ - "class Person:\n", - " def __init__(self, name, login, system_id):\n", - " print(\"Person.__init__\")\n", - " self.name = name\n", - " self._login = login\n", - " self.__system_id = system_id\n", - "\n", - " def print_info(self):\n", - " print(f\"Person.print_info: {self.name=}, {self._login=}, {self.__system_id=}\")\n", - "\n", - "\n", - "class Student(Person):\n", - " def __init__(self, school, *args, **kwargs):\n", - " print(\"Student.__init__\")\n", - " super().__init__(*args, **kwargs)\n", - "\n", - " self.school = school\n", - "\n", - " def print_info(self):\n", - " print(\n", - " f\"Student.print_info: \"\n", - " f\"{self.school=}, {self.name=}, \"\n", - " f\"{self._login=}, {self.__system_id=}\"\n", - " )\n", - "\n", - "\n", - "steve = Student(\"hse\", \"Steven\", \"steve\", 123)\n", - "print(steve.__dict__)\n", - "steve.print_info()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7cb1b685-9612-4fc2-a67f-435179162875", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 135, - "id": "16edc530-ff9f-40d3-a712-4e0470baa428", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person.__init__\n", - "{'name': 'Steven', '_login': 'steve'}\n", - "Person.print_info: self.name='Steven', self._login='steve', self.__system_id='default_system_id', Person.__system_id='default_system_id'\n" - ] - } - ], - "source": [ - "class Person:\n", - " __system_id = \"default_system_id\"\n", - "\n", - " def __init__(self, name, login, system_id):\n", - " print(\"Person.__init__\")\n", - " self.name = name\n", - " self._login = login\n", - " self.__system_id = system_id\n", - "\n", - " @property\n", - " def system_id(self):\n", - " return self.__system_id\n", - "\n", - " def print_info(self):\n", - " print(\n", - " f\"Person.print_info: {self.name=}, {self._login=}, \"\n", - " f\"{self.__system_id=}, {Person.__system_id=}\"\n", - " )\n", - "\n", - "\n", - "steve = Person(\"Steven\", \"steve\", 123)\n", - "print(steve.__dict__)\n", - "steve.print_info()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d02f7935-2f57-4ca8-87d3-b4ab80b7683a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 137, - "id": "bea47e6b-b203-42f5-9cd3-c43a7459b6d5", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Student.__init__\n", - "Person.__init__\n", - "{'name': 'Student_Steven', '_login': 'Student_steve', '_Person__system_id': 123, '_Student__system_id': 10123, 'school': 'hse'}\n", - "Student.print_info: self.school='hse', self.name='Student_Steven', self._login='Student_steve', self.system_id=123, self.__system_id=10123\n" - ] - } - ], - "source": [ - "class Person:\n", - " def __init__(self, name, login, system_id):\n", - " print(\"Person.__init__\")\n", - " self.name = name\n", - " self._login = login\n", - " self.__system_id = system_id\n", - "\n", - " @property\n", - " def system_id(self):\n", - " return self.__system_id\n", - "\n", - " def print_info(self):\n", - " print(f\"Person.print_info: {self.name=}, {self._login=}, {self.__system_id=}\")\n", - "\n", - "\n", - "class Student(Person):\n", - " def __init__(self, school, name, login, system_id):\n", - " print(\"Student.__init__\")\n", - " super().__init__(name, login, system_id)\n", - "\n", - " self.name = \"Student_\" + name\n", - " self._login = \"Student_\" + login\n", - " self.__system_id = 10000 + system_id\n", - " self.school = school\n", - "\n", - " def print_info(self):\n", - " print(\n", - " f\"Student.print_info: \"\n", - " f\"{self.school=}, {self.name=}, \"\n", - " f\"{self._login=}, {self.system_id=}, {self.__system_id=}\"\n", - " )\n", - "\n", - "\n", - "steve = Student(\"hse\", \"Steven\", \"steve\", 123)\n", - "print(steve.__dict__)\n", - "steve.print_info()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b1b38aa0-63a4-4c6f-9304-285c134d27ff", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 142, - "id": "dc01eb96-2220-4f31-8246-2c67ab181d33", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Student.__init__\n", - "Person.__init__\n", - "{'name': 'Student_Steven', '_login': 'Student_steve', '_Person__system_id': 123, '_Student__system_id': 10123, 'school': 'hse'}\n", - "Student.print_info: self.school='hse', self.name='Student_Steven', self._login='Student_steve', self.system_id=123, self.__system_id=10123\n" - ] - } - ], - "source": [ - "class Person:\n", - " def __init__(self, name, login, system_id):\n", - " print(\"Person.__init__\")\n", - " self.name = name\n", - " self._login = login\n", - " self.__system_id = system_id\n", - "\n", - " @property\n", - " def system_id(self):\n", - " return self.__system_id\n", - "\n", - " def print_info(self):\n", - " print(f\"Person.print_info: {self.name=}, {self._login=}, {self.__system_id=}\")\n", - "\n", - "\n", - "class Student(Person):\n", - " def __init__(self, school, name, login, system_id):\n", - " print(\"Student.__init__\")\n", - " super().__init__(name, login, system_id)\n", - "\n", - " self.name = \"Student_\" + name\n", - " self._login = \"Student_\" + login\n", - " self.__system_id = 10000 + system_id\n", - " self.school = school\n", - "\n", - " def print_info(self):\n", - " print(\n", - " f\"Student.print_info: \"\n", - " f\"{self.school=}, {self.name=}, \"\n", - " f\"{self._login=}, {self.system_id=}, {self.__system_id=}\"\n", - " )\n", - "\n", - "\n", - "class HSEStudent(Student):\n", - " pass\n", - "\n", - "\n", - "steve = HSEStudent(\"hse\", \"Steven\", \"steve\", 123)\n", - "print(steve.__dict__)\n", - "steve.print_info()" - ] - }, - { - "cell_type": "code", - "execution_count": 144, - "id": "108e796a-fe2c-4cc7-b5e6-84f8aa8a51fb", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(123, 'Student_Steven')" - ] - }, - "execution_count": 144, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.system_id, steve.name" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "423fa1ff-2d9c-4a8b-be2a-ab8f25d3962f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 141, - "id": "fcd3f69e-0810-4ff3-9029-131ffb6eb54c", - "metadata": {}, - "outputs": [], - "source": [ - "class Person(Person): pass" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a138537b-1331-4585-bf77-adecfb53dd51", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "58572a08-082f-4ff5-8445-c32d4dc0387e", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ba758b4c-3eab-4ad4-b141-98634796e8fb", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "f1cf442a-90dc-4ca9-997d-9e9a13eb1df8", - "metadata": {}, - "source": [ - "# Дескрипторы" - ] - }, - { - "cell_type": "code", - "execution_count": 157, - "id": "3a387bf5-fae1-4d4b-ad21-f2164929cc2b", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__set__ obj=<__main__.PersonTable object at 0x10bc063c0>, val=99\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10c55dd10>, val=42\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10bc063c0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55dd10>, objtype=\n", - "42 42\n", - "------\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10bc063c0>, val=882\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10bc063c0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55dd10>, objtype=\n", - "882 882\n" - ] - } - ], - "source": [ - "# BAD (!)\n", - "\n", - "class IntField:\n", - " def __init__(self):\n", - " self.val = None\n", - "\n", - " def __get__(self, obj, objtype):\n", - " print(f\"IntField.__get__ {obj=}, {objtype=}\")\n", - " \n", - " return self.val\n", - " \n", - " def __set__(self, obj, val):\n", - " print(f\"IntField.__set__ {obj=}, {val=}\")\n", - " \n", - " self.val = val\n", - "\n", - " def __delete__(self, obj):\n", - " print(f\"IntField.__delete__ {obj=}\")\n", - "\n", - "\n", - "class PersonTable:\n", - " age = IntField()\n", - "\n", - " def __init__(self, age):\n", - " self.age = age\n", - "\n", - "\n", - "class Student(PersonTable):\n", - " pass\n", - "\n", - "\n", - "pers1 = PersonTable(99)\n", - "pers2 = PersonTable(42)\n", - "\n", - "print(pers1.age, pers2.age)\n", - "print(\"------\")\n", - "\n", - "pers1.age = 882\n", - "print(pers1.age, pers2.age)" - ] - }, - { - "cell_type": "code", - "execution_count": 152, - "id": "d2191368-1fda-491c-97e2-29e2a3ef892e", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{}" - ] - }, - "execution_count": 152, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 153, - "id": "8f466c7f-e340-40d0-9fdf-00d4c43299c8", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'__module__': '__main__',\n", - " '__firstlineno__': 21,\n", - " 'age': <__main__.IntField at 0x10bc05fd0>,\n", - " '__init__': ,\n", - " '__static_attributes__': ('age',),\n", - " '__dict__': ,\n", - " '__weakref__': ,\n", - " '__doc__': None})" - ] - }, - "execution_count": 153, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "PersonTable.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 154, - "id": "a5dc551e-6955-4e42-8b1e-e25e6a16619c", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__get__ obj=None, objtype=\n" - ] - }, - { - "data": { - "text/plain": [ - "99" - ] - }, - "execution_count": 154, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "PersonTable.age" - ] - }, - { - "cell_type": "code", - "execution_count": 156, - "id": "d529d6ed-122e-4ec1-9e9b-a88a11d94bcc", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__get__ obj=<__main__.PersonTable object at 0x10bc06270>, objtype=\n" - ] - }, - { - "data": { - "text/plain": [ - "99" - ] - }, - "execution_count": 156, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.age" - ] - }, - { - "cell_type": "code", - "execution_count": 159, - "id": "ecea6ef8-57f6-4118-8329-db271c5dd27e", - "metadata": {}, - "outputs": [], - "source": [ - "PersonTable.age = 100" - ] - }, - { - "cell_type": "code", - "execution_count": 160, - "id": "e26fcd81-6d5e-43ab-ba43-df067dea6d23", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "100" - ] - }, - "execution_count": 160, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "PersonTable.age" - ] - }, - { - "cell_type": "code", - "execution_count": 161, - "id": "4c124218-5141-4908-beec-6940cf51b297", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "100 100\n" - ] - } - ], - "source": [ - "print(pers1.age, pers2.age)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "df513ef4-54ed-45c1-aaef-d43ec491ce0f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bb33c3da-4c4d-4ede-b5c8-b89c0e1e80f8", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 162, - "id": "96ed9c56-1da1-4cf4-b824-0bf8314ce3dc", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__set__ obj=<__main__.PersonTable object at 0x10bc06510>, val=99\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10c55e210>, val=42\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10bc06510>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55e210>, objtype=\n", - "99 42\n", - "------\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10bc06510>, val=882\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10bc06510>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55e210>, objtype=\n", - "882 42\n" - ] - } - ], - "source": [ - "# BAD (!)\n", - "\n", - "class IntField:\n", - " def __init__(self):\n", - " self._name = \"_hidden_int\"\n", - "\n", - " def __get__(self, obj, objtype):\n", - " print(f\"IntField.__get__ {obj=}, {objtype=}\")\n", - "\n", - " if obj is None:\n", - " return None\n", - "\n", - " return getattr(obj, self._name)\n", - " \n", - " def __set__(self, obj, val):\n", - " print(f\"IntField.__set__ {obj=}, {val=}\")\n", - "\n", - " # obj.__dict__[self._name] = val\n", - " return setattr(obj, self._name, val)\n", - "\n", - "\n", - "class PersonTable:\n", - " age = IntField()\n", - "\n", - " def __init__(self, age):\n", - " self.age = age\n", - "\n", - "\n", - "class Student(PersonTable):\n", - " pass\n", - "\n", - "\n", - "pers1 = PersonTable(99)\n", - "pers2 = PersonTable(42)\n", - "\n", - "print(pers1.age, pers2.age)\n", - "print(\"------\")\n", - "\n", - "pers1.age = 882\n", - "print(pers1.age, pers2.age)" - ] - }, - { - "cell_type": "code", - "execution_count": 163, - "id": "96918f91-1f86-4eac-a962-bed915fcd4ab", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "({'_hidden_int': 882}, {'_hidden_int': 42})" - ] - }, - "execution_count": 163, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers1.__dict__, pers2.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "084e9359-4090-4857-8df0-2b1f16a65c33", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 169, - "id": "e07dac72-c4e9-4a3e-969a-b55cdcef440d", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__set__ obj=<__main__.PersonTable object at 0x10b7530e0>, val=99\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10b7530e0>, val=1980\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10c55e710>, val=42\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10c55e710>, val=2025\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10b7530e0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10b7530e0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55e710>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55e710>, objtype=\n", - "1980 1980 2025 2025\n", - "------\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10b7530e0>, val=882\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10b7530e0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10b7530e0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55e710>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55e710>, objtype=\n", - "882 882 2025 2025\n", - "--------\n", - "\n", - "{'_hidden_int': 882} {'_hidden_int': 2025}\n" - ] - } - ], - "source": [ - "# BAD (!)\n", - "\n", - "class IntField:\n", - " def __init__(self):\n", - " self._name = \"_hidden_int\"\n", - "\n", - " def __get__(self, obj, objtype):\n", - " print(f\"IntField.__get__ {obj=}, {objtype=}\")\n", - "\n", - " if obj is None:\n", - " return None\n", - "\n", - " return getattr(obj, self._name)\n", - " \n", - " def __set__(self, obj, val):\n", - " print(f\"IntField.__set__ {obj=}, {val=}\")\n", - "\n", - " if not (isinstance(val, int) and val >= 0):\n", - " raise ValueError(\"wrong int\")\n", - "\n", - " # obj.__dict__[self._name] = val\n", - " return setattr(obj, self._name, val)\n", - "\n", - "\n", - "class PersonTable:\n", - " age = IntField()\n", - " year = IntField()\n", - "\n", - " def __init__(self, age, year):\n", - " self.age = age\n", - " self.year = year\n", - "\n", - "\n", - "class Student(PersonTable):\n", - " pass\n", - "\n", - "\n", - "pers1 = PersonTable(99, 1980)\n", - "pers2 = PersonTable(42, 2025)\n", - "\n", - "print(pers1.age, pers1.year, pers2.age, pers2.year)\n", - "print(\"------\")\n", - "\n", - "pers1.age = 882\n", - "print(pers1.age, pers1.year, pers2.age, pers2.year)\n", - "\n", - "print(\"--------\\n\")\n", - "print(pers1.__dict__, pers2.__dict__)" - ] - }, - { - "cell_type": "code", - "execution_count": 165, - "id": "81bc0901-61c2-4a93-8f58-9e8ff00acd10", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__set__ obj=<__main__.PersonTable object at 0x10b752510>, val=100\n" - ] - } - ], - "source": [ - "pers1.age = 100" - ] - }, - { - "cell_type": "code", - "execution_count": 166, - "id": "a8d97e40-fc0a-4b99-b372-76e92299e4d2", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__get__ obj=<__main__.PersonTable object at 0x10b752510>, objtype=\n" - ] - }, - { - "data": { - "text/plain": [ - "100" - ] - }, - "execution_count": 166, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers1.age" - ] - }, - { - "cell_type": "code", - "execution_count": 167, - "id": "e3d5d1db-7680-4f75-b28e-c9c2b750aa75", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__set__ obj=<__main__.PersonTable object at 0x10b752510>, val=-10\n" - ] - }, - { - "ename": "ValueError", - "evalue": "wrong int", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mValueError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[167]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43mpers1\u001b[49m\u001b[43m.\u001b[49m\u001b[43mage\u001b[49m = -\u001b[32m10\u001b[39m\n", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[164]\u001b[39m\u001b[32m, line 19\u001b[39m, in \u001b[36mIntField.__set__\u001b[39m\u001b[34m(self, obj, val)\u001b[39m\n\u001b[32m 16\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mIntField.__set__ \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mobj\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m, \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mval\u001b[38;5;132;01m=}\u001b[39;00m\u001b[33m\"\u001b[39m)\n\u001b[32m 18\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28misinstance\u001b[39m(val, \u001b[38;5;28mint\u001b[39m) \u001b[38;5;129;01mand\u001b[39;00m val >= \u001b[32m0\u001b[39m):\n\u001b[32m---> \u001b[39m\u001b[32m19\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[33m\"\u001b[39m\u001b[33mwrong int\u001b[39m\u001b[33m\"\u001b[39m)\n\u001b[32m 21\u001b[39m \u001b[38;5;66;03m# obj.__dict__[self._name] = val\u001b[39;00m\n\u001b[32m 22\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28msetattr\u001b[39m(obj, \u001b[38;5;28mself\u001b[39m._name, val)\n", - "\u001b[31mValueError\u001b[39m: wrong int" - ] - } - ], - "source": [ - "pers1.age = -10" - ] - }, - { - "cell_type": "code", - "execution_count": 168, - "id": "25641992-717b-4f21-8e82-cd51e9339938", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__get__ obj=<__main__.PersonTable object at 0x10b752510>, objtype=\n" - ] - }, - { - "data": { - "text/plain": [ - "100" - ] - }, - "execution_count": 168, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers1.age" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "34e984d3-fb45-488c-a6f8-23ad60cb6b6e", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3b56e9d7-6f90-4287-9f28-5c832ec44562", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4a9063f8-d40f-4a72-8a9c-bcca6f1cef05", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "89674fda-3f3f-43b9-8be2-43993244d680", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 172, - "id": "00e3241d-cd80-427e-8414-092db4b8e06d", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Int set_name owner=, name='age'\n", - "Int set_name owner=, name='year'\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10bc063c0>, val=99\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10bc063c0>, val=1980\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10c55ead0>, val=42\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10c55ead0>, val=2025\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10bc063c0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10bc063c0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55ead0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55ead0>, objtype=\n", - "99 1980 42 2025\n", - "------\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10bc063c0>, val=882\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10bc063c0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10bc063c0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55ead0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10c55ead0>, objtype=\n", - "882 1980 42 2025\n", - "--------\n", - "\n", - "{'_hidden_int_age': 882, '_hidden_int_year': 1980} {'_hidden_int_age': 42, '_hidden_int_year': 2025}\n" - ] - } - ], - "source": [ - "# VALID\n", - "\n", - "class IntField:\n", - " def __init__(self):\n", - " self._name = None\n", - "\n", - " def __set_name__(self, owner, name):\n", - " print(f\"Int set_name {owner=}, {name=}\")\n", - " self._name = f\"_hidden_int_{name}\"\n", - "\n", - " def __get__(self, obj, objtype):\n", - " print(f\"IntField.__get__ {obj=}, {objtype=}\")\n", - "\n", - " if obj is None:\n", - " return None\n", - "\n", - " return getattr(obj, self._name)\n", - " \n", - " def __set__(self, obj, val):\n", - " print(f\"IntField.__set__ {obj=}, {val=}\")\n", - "\n", - " if not (isinstance(val, int) and val >= 0):\n", - " raise ValueError(\"wrong int\")\n", - "\n", - " # obj.__dict__[self._name] = val\n", - " return setattr(obj, self._name, val)\n", - "\n", - "\n", - "class PersonTable:\n", - " age = IntField()\n", - " year = IntField()\n", - "\n", - " def __init__(self, age, year):\n", - " self.age = age\n", - " self.year = year\n", - "\n", - "\n", - "class Student(PersonTable):\n", - " pass\n", - "\n", - "\n", - "pers1 = PersonTable(99, 1980)\n", - "pers2 = PersonTable(42, 2025)\n", - "\n", - "print(pers1.age, pers1.year, pers2.age, pers2.year)\n", - "print(\"------\")\n", - "\n", - "pers1.age = 882\n", - "print(pers1.age, pers1.year, pers2.age, pers2.year)\n", - "\n", - "print(\"--------\\n\")\n", - "print(pers1.__dict__, pers2.__dict__)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c2c52589-5fef-4e2b-b6b1-92946215334f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "47e5d403-2414-46e2-9f1c-643c76b27d7a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0bc55dfa-d0c8-46bb-97c8-fd4d560a29ad", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f9a81ec9-0dcd-472c-ab64-9ea1ca606564", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f2827567-7878-4bea-a5e8-8d4e0f5430bf", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 179, - "id": "c2265f1e-1d4b-4556-96ac-13d9d275d746", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Int set_name owner=, name='age'\n", - "Name set_name owner=, name='name'\n", - "IntField.__set__ obj=<__main__.PersonTable object at 0x10b7530e0>, val=99\n", - "{'_hidden_int_age': 99, '_hidden_name_name': 'steve'}\n", - "NameField.__get__ obj=<__main__.PersonTable object at 0x10b7530e0>, objtype=\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10b7530e0>, objtype=\n", - "steve 99\n" - ] - } - ], - "source": [ - "# VALID\n", - "\n", - "class IntField:\n", - " def __init__(self):\n", - " self._name = None\n", - "\n", - " def __set_name__(self, owner, name):\n", - " print(f\"Int set_name {owner=}, {name=}\")\n", - " self._name = f\"_hidden_int_{name}\"\n", - "\n", - " def __get__(self, obj, objtype):\n", - " print(f\"IntField.__get__ {obj=}, {objtype=}\")\n", - "\n", - " if obj is None:\n", - " return None\n", - "\n", - " return getattr(obj, self._name)\n", - " \n", - " def __set__(self, obj, val):\n", - " print(f\"IntField.__set__ {obj=}, {val=}\")\n", - "\n", - " if not (isinstance(val, int) and val >= 0):\n", - " raise ValueError(\"wrong int\")\n", - "\n", - " # obj.__dict__[self._name] = val\n", - " return setattr(obj, self._name, val)\n", - "\n", - "\n", - "class NameField:\n", - " def __init__(self):\n", - " self._name = None\n", - "\n", - " def __set_name__(self, owner, name):\n", - " print(f\"Name set_name {owner=}, {name=}\")\n", - " self._name = f\"_hidden_name_{name}\"\n", - "\n", - " def __get__(self, obj, objtype):\n", - " print(f\"NameField.__get__ {obj=}, {objtype=}\")\n", - "\n", - " if obj is None:\n", - " return None\n", - "\n", - " return getattr(obj, self._name)\n", - "\n", - "\n", - "class PersonTable:\n", - " age = IntField()\n", - " name = NameField()\n", - "\n", - " def __init__(self, age, name):\n", - " self.age = age\n", - " self._hidden_name_name = name\n", - "\n", - "\n", - "pers = PersonTable(99, \"steve\")\n", - "print(pers.__dict__)\n", - "print(pers.name, pers.age)" - ] - }, - { - "cell_type": "code", - "execution_count": 180, - "id": "67bd2e1f-420f-4979-a3d0-5a6228f0e98f", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__get__ obj=<__main__.PersonTable object at 0x10b7530e0>, objtype=\n" - ] - }, - { - "data": { - "text/plain": [ - "99" - ] - }, - "execution_count": 180, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.age" - ] - }, - { - "cell_type": "code", - "execution_count": 181, - "id": "98197242-ddf0-4778-8045-366f812f377f", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "NameField.__get__ obj=<__main__.PersonTable object at 0x10b7530e0>, objtype=\n" - ] - }, - { - "data": { - "text/plain": [ - "'steve'" - ] - }, - "execution_count": 181, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.name" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9da54288-e3ad-4a60-b364-9b04bcf6ebcd", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 182, - "id": "1553c03b-5ee9-4c2a-86a5-ef950af28153", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__set__ obj=<__main__.PersonTable object at 0x10b7530e0>, val=882\n", - "IntField.__get__ obj=<__main__.PersonTable object at 0x10b7530e0>, objtype=\n" - ] - }, - { - "data": { - "text/plain": [ - "882" - ] - }, - "execution_count": 182, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.age = 882\n", - "pers.age" - ] - }, - { - "cell_type": "code", - "execution_count": 183, - "id": "75634b64-aaa3-477e-80d3-1cbe18fb68ea", - "metadata": {}, - "outputs": [], - "source": [ - "pers.name = \"newName\"" - ] - }, - { - "cell_type": "code", - "execution_count": 185, - "id": "57374a6d-efcc-4953-83b4-8ecabe9f4f5f", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'newName'" - ] - }, - "execution_count": 185, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.name" - ] - }, - { - "cell_type": "code", - "execution_count": 187, - "id": "05357379-07cb-47c0-b938-e5d84b03eb22", - "metadata": {}, - "outputs": [], - "source": [ - "pers.__dict__[\"age\"] = -20" - ] - }, - { - "cell_type": "code", - "execution_count": 188, - "id": "0193bf87-623c-42f4-b092-fa962725a6d0", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'_hidden_int_age': 882,\n", - " '_hidden_name_name': 'steve',\n", - " 'name': 'newName',\n", - " 'age': -20}" - ] - }, - "execution_count": 188, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.__dict__\n" - ] - }, - { - "cell_type": "code", - "execution_count": 189, - "id": "50493d9c-fe38-46a7-b3ea-eb1a8c8f8cea", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "IntField.__get__ obj=<__main__.PersonTable object at 0x10b7530e0>, objtype=\n" - ] - }, - { - "data": { - "text/plain": [ - "882" - ] - }, - "execution_count": 189, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.age" - ] - }, - { - "cell_type": "code", - "execution_count": 190, - "id": "32475ff9-5517-4e37-b992-5d1f74795ec4", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'newName'" - ] - }, - "execution_count": 190, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.name" - ] - }, - { - "cell_type": "code", - "execution_count": 191, - "id": "90f56e7d-c2a6-43b6-b501-1eab7199a5df", - "metadata": {}, - "outputs": [], - "source": [ - "del pers.name" - ] - }, - { - "cell_type": "code", - "execution_count": 192, - "id": "a060bfd7-681b-436a-93cd-ab3441f2c725", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'_hidden_int_age': 882, '_hidden_name_name': 'steve', 'age': -20}" - ] - }, - "execution_count": 192, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.__dict__\n" - ] - }, - { - "cell_type": "code", - "execution_count": 193, - "id": "6817cc46-8cd2-4b6d-8373-e3dab813fc69", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "NameField.__get__ obj=<__main__.PersonTable object at 0x10b7530e0>, objtype=\n" - ] - }, - { - "data": { - "text/plain": [ - "'steve'" - ] - }, - "execution_count": 193, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pers.name" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7666e3a6-5be9-45f6-838f-a231920f45b3", - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.13.2" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/lesson-04/homework.md b/lesson-04/homework.md deleted file mode 100644 index bd51c5e..0000000 --- a/lesson-04/homework.md +++ /dev/null @@ -1,76 +0,0 @@ -# Домашнее задание #04 (дескрипторы, метаклассы, ABC) - -### 1. Метакласс, который в начале названий всех атрибутов и методов, кроме магических, добавляет префикс "custom_" - Подменяться должны атрибуты класса и атрибуты экземпляра класса, в том числе добавленные после выполнения конструктора (dynamic в примере). - -```py - class CustomMeta(...): - pass - - - class CustomClass(metaclass=CustomMeta): - x = 50 - - def __init__(self, val=99): - self.val = val - - def line(self): - return 100 - - def __str__(self): - return "Custom_by_metaclass" - - - assert CustomClass.custom_x == 50 - CustomClass.x # ошибка - - inst = CustomClass() - assert inst.custom_x == 50 - assert inst.custom_val == 99 - assert inst.custom_line() == 100 - assert str(inst) == "Custom_by_metaclass" - - inst.x # ошибка - inst.val # ошибка - inst.line() # ошибка - inst.yyy # ошибка - - inst.dynamic = "added later" - assert inst.custom_dynamic == "added later" - inst.dynamic # ошибка -``` - - -### 2. Дескрипторы с проверками типов и значений данных - Нужно сделать три дескриптора для какой-то области интереса (наука, финансы, хобби и тд), но если совсем не получается, то можно использовать шаблона ниже в качестве основы. - У дескрипторов должен быть базовый класс с абстрактным методом-проверкой, который наследующие классы должны будут реализовать. - -```py - class Base...: - pass - - class Integer: - pass - - class String: - pass - - class PositiveInteger: - pass - - class Data: - num = Integer() - name = String() - price = PositiveInteger() - - def __init__(...): - .... -``` - - -### 3. Тесты метакласса и дескрипторов в отдельных модулях - -### 4. Зеленый пайплайн в репе -Обязательно: тесты, покрытие, flake8, pylint. -Опционально можно добавить другие инструменты, например, mypy и black. -Покрытие тестов должно составлять не менее 90%. diff --git a/lesson-04/lesson-04.pdf b/lesson-04/lesson-04.pdf deleted file mode 100644 index 2882855..0000000 Binary files a/lesson-04/lesson-04.pdf and /dev/null differ diff --git a/lesson-05/class_05.ipynb b/lesson-05/class_05.ipynb deleted file mode 100644 index 8a058db..0000000 --- a/lesson-05/class_05.ipynb +++ /dev/null @@ -1,2417 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 1, - "id": "36130ed6-9784-470d-aa6e-6cfaa67f21e9", - "metadata": {}, - "outputs": [], - "source": [ - "class Person:\n", - " def eat(self):\n", - " return 42\n", - "\n", - "\n", - "def fn():\n", - " return 42" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "2b831569-2938-486c-adc6-b91f83c24a24", - "metadata": {}, - "outputs": [], - "source": [ - "steve = Person() # Person = type(...)\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7cc01811-b383-4fb3-a873-0823fade7c53", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "635956d1-7cd1-431f-9fc2-c0a54a3ecba9", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "\u001b[31mInit signature:\u001b[39m type(self, /, *args, **kwargs)\n", - "\u001b[31mDocstring:\u001b[39m \n", - "type(object) -> the object's type\n", - "type(name, bases, dict, **kwds) -> a new type\n", - "\u001b[31mType:\u001b[39m type\n", - "\u001b[31mSubclasses:\u001b[39m ABCMeta, EnumType, _AnyMeta, NamedTupleMeta, _TypedDictMeta, _ABC, MetaHasDescriptors, _TzSingleton, _TzFactory, StyleMeta, ..." - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "type?" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "75292028-04f7-48da-9662-2665b27f03bc", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(str, list, NoneType)" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(\"kwjdkj\"), type([1, 3]), type(None)" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "a591547e-5c24-4947-937c-0401e4be9dc7", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "function" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(fn)" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "95f42170-f3c6-4da8-8352-4c99e6dc04ea", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(__main__.Person, method)" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(Person()), type(Person().eat)" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "1e8af196-8078-469d-b440-3bf1339a2f91", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(type, type, type)" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(Person), type(object), type(str)" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "f4fc7174-877c-4a77-9828-5d28b3b9fb67", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "issubclass(type, object)" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "1fa3fbf5-7944-4c7e-8760-8905fe0faa17", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(object, type)" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "ad3e913d-2a5d-4a7d-bd34-12bbfca87035", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(True, True, True)" - ] - }, - "execution_count": 12, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "issubclass(object, object), issubclass(type, type), issubclass(Person, Person)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "7717946c-1c91-4aa6-a7c9-ac964a17b5a8", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(False, True, True, False)" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "issubclass(object, type), issubclass(type, object), issubclass(Person, object), issubclass(Person, type)" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "bf183314-2451-42fb-af74-c8b9b33251b4", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(True, True, True)" - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(object, type), isinstance(Person, type), isinstance(str, type)" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "4d12e947-8e96-474a-a422-c2cfa33228ad", - "metadata": {}, - "outputs": [], - "source": [ - "steve = Person() # Person = type(...)" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "8c665a04-05a3-4f7c-aac0-b1a684e32ece", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 18, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(steve, Person)" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "72566487-a627-4a65-b0cc-fc918e548ce6", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "False" - ] - }, - "execution_count": 19, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(Person, Person)" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "e14bdd07-7eca-4424-b541-952f116e29db", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(True, True, True)" - ] - }, - "execution_count": 20, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(object, type), isinstance(Person, type), isinstance(str, type)" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "2c9af56e-1404-4772-a553-9dd049cde640", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(True, True, True)" - ] - }, - "execution_count": 21, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(type, object), isinstance(str, object), isinstance(Person, object)" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "a48134f8-f64b-4976-b4b0-0b5ae8ea2581", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(type, object)" - ] - }, - "execution_count": 24, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type.__class__.__mro__" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "367cb059-23b5-4eac-bf90-0188c4bd7e16", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(False, False, True, True)" - ] - }, - "execution_count": 28, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(Person, Person), isinstance(str, str), isinstance(type, type), isinstance(object, object)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b29e71cd-0faf-44f6-b20f-e7098fdf4f70", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d2a841da-ed04-48be-9ca0-56aa4c095b5a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "abe8fe05-30ce-41ee-b3f2-b9101529a8b8", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "705726d0-ab65-4a31-9ea1-2b6cbeeae132", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4b98a102-8777-4a17-8f87-90c394c89e1c", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "b004596c-e434-422c-9726-81f28feb4783", - "metadata": {}, - "outputs": [], - "source": [ - "class Foo:\n", - " name = \"foo_name\"\n", - "\n", - " def __init__(self, val):\n", - " self.val = val\n", - "\n", - "Boo = type(\"Boo\", (Foo,), {\"age\": 99})" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "b6a03193-0ba5-45dd-880a-540f93507009", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(__main__.Foo, __main__.Boo)" - ] - }, - "execution_count": 30, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Foo, Boo" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "1596a4c3-c0dd-4754-a6fa-4239f6830177", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'__module__': '__main__',\n", - " '__firstlineno__': 1,\n", - " 'name': 'foo_name',\n", - " '__init__': ,\n", - " '__static_attributes__': ('val',),\n", - " '__dict__': ,\n", - " '__weakref__': ,\n", - " '__doc__': None})" - ] - }, - "execution_count": 31, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Foo.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "e2f2232e-98e3-4a18-acf8-6fde8d92df53", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'age': 99, '__module__': '__main__', '__doc__': None})" - ] - }, - "execution_count": 32, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Boo.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "9eeb707d-ab84-4bca-a878-3f1c59a8f5a8", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'foo_name'" - ] - }, - "execution_count": 33, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Boo.name" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "f2db82e0-41a6-43fd-b017-3bbfb037ea92", - "metadata": {}, - "outputs": [], - "source": [ - "b = Boo(42)" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "6f589fe2-42b4-4ccd-b3e9-4415b8533913", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "42" - ] - }, - "execution_count": 35, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "b.val" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "d86a7c2b-b06b-4b16-9000-8c7224bc44bd", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Boo'" - ] - }, - "execution_count": 36, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Boo.__name__" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "7c279954-289c-4e38-baa8-bab8d029af35", - "metadata": {}, - "outputs": [], - "source": [ - "Other = type(\"Zoo\", (Foo,), {\"age\": 99})" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "id": "5c472b61-c7e2-4373-a89a-b72df959ecd3", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Zoo'" - ] - }, - "execution_count": 38, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Other.__name__" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "bf930ed1-c580-4ffc-8e97-031c3b5b14f3", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Foo'" - ] - }, - "execution_count": 39, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Foo.__name__" - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "id": "3c73cf5b-c012-4994-b99b-b424fdd3f179", - "metadata": {}, - "outputs": [], - "source": [ - "OtherFoo = Foo" - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "id": "2afbbd92-6a0a-4b20-bd24-6ab57398fd3a", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Foo'" - ] - }, - "execution_count": 41, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "OtherFoo.__name__" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "81ffbf2b-67f7-436f-87de-3cb5ff2cd6f0", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ea11a038-86b8-49a1-b220-4ce5ae185a1f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 42, - "id": "4ad513e7-f37e-4c02-9c1f-053388336d68", - "metadata": {}, - "outputs": [], - "source": [ - "class Foo:\n", - " name = \"foo_name\"\n", - "\n", - " def __init__(self, val):\n", - " self.val = val\n", - "\n", - "Boo = type(\n", - " \"Boo\",\n", - " (Foo,),\n", - " {\n", - " \"age\": 99,\n", - " \"print\": lambda self: f\"{self=}: {self.val=}\"\n", - " },\n", - ")" - ] - }, - { - "cell_type": "code", - "execution_count": 43, - "id": "8f23d7d3-fa62-4b4c-828e-8880ca641f3a", - "metadata": {}, - "outputs": [], - "source": [ - "b = Boo(99)" - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "id": "db2d5506-64e5-4cfe-be62-2ad4c68d4feb", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "( of <__main__.Boo object at 0x110bd0440>>,\n", - " <__main__.Boo at 0x110bd0440>)" - ] - }, - "execution_count": 45, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "b.print, b.print.__self__" - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "id": "45ea70cc-87ae-4d0f-a45f-6767996ecaa3", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'self=<__main__.Boo object at 0x110bd0440>: self.val=99'" - ] - }, - "execution_count": 46, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "b.print()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4495e90e-d921-4c09-85bc-4e84f9d3567d", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 55, - "id": "d8230222-7aea-4689-a9e8-7d78ea0c5094", - "metadata": {}, - "outputs": [], - "source": [ - "class Foo:\n", - " __priv = \"private_attr\"\n", - " name = \"foo_name\"\n", - "\n", - " def __init__(self, val):\n", - " self.val = val\n", - "\n", - "Boo = type(\n", - " \"Boo\",\n", - " (Foo,),\n", - " {\n", - " \"__age\": 99,\n", - " \"print\": lambda self: f\"{self=}: {self.__age=}\"\n", - " },\n", - ")" - ] - }, - { - "cell_type": "code", - "execution_count": 56, - "id": "2fe93284-fdd5-43ef-a55b-0930191ddd8d", - "metadata": {}, - "outputs": [], - "source": [ - "b = Boo(99)" - ] - }, - { - "cell_type": "code", - "execution_count": 57, - "id": "a5686c85-fde4-4a42-b022-160c7a859591", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'self=<__main__.Boo object at 0x110a25be0>: self.__age=99'" - ] - }, - "execution_count": 57, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "b.print()" - ] - }, - { - "cell_type": "code", - "execution_count": 58, - "id": "f2178c5a-20a4-4225-a2f7-ca26bcf7ac1c", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'__age': 99,\n", - " 'print': (self)>,\n", - " '__module__': '__main__',\n", - " '__doc__': None})" - ] - }, - "execution_count": 58, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Boo.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 59, - "id": "e8277782-bd5c-4b7a-8905-0b4629f60c12", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'__module__': '__main__',\n", - " '__firstlineno__': 1,\n", - " '_Foo__priv': 'private_attr',\n", - " 'name': 'foo_name',\n", - " '__init__': ,\n", - " '__static_attributes__': ('val',),\n", - " '__dict__': ,\n", - " '__weakref__': ,\n", - " '__doc__': None})" - ] - }, - "execution_count": 59, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Foo.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 60, - "id": "9428fffe-e671-42be-96a8-fd81c67c1eea", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "99" - ] - }, - "execution_count": 60, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "b.__age" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b5134195-37dd-4f81-9131-1b6793e36c0d", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cca38c55-7444-4f9c-b54c-9319ccca7a77", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8094a852-a866-4df5-b6ca-094c4a9ab16b", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 61, - "id": "75e2b21b-6ac1-4ace-8c4d-5d32035c2f1d", - "metadata": {}, - "outputs": [], - "source": [ - "class AMeta(type):\n", - " def __new__(mcs, name, bases, classdict, **kwargs):\n", - " print(f\"AMeta.__new__ {name=}, {bases=}, {classdict=}, {kwargs=}\")\n", - "\n", - " cls = super().__new__(mcs, name, bases, classdict)\n", - " print(\"AMeta __new__\", cls)\n", - "\n", - " return cls\n", - "\n", - " def __init__(cls, name, bases, classdict, **kwargs):\n", - " print(\"AMeta __init__\", cls, name, bases, classdict)\n", - " super().__init__(name, bases, classdict, **kwargs)\n", - "\n", - " def __call__(cls, *args, **kwargs):\n", - " print(\"AMeta __call__\", cls, args, kwargs)\n", - " return super().__call__(*args, **kwargs)\n", - "\n", - " @classmethod\n", - " def __prepare__(mcs, name, bases, **kwargs):\n", - " print(\"AMeta __prepare__\", mcs, name, bases, kwargs)\n", - " \n", - " return {\"added_attr_a\": 2, \"added_attr_b\": 99}" - ] - }, - { - "cell_type": "code", - "execution_count": 62, - "id": "8b2cc029-e5fa-4d5d-8471-81afbd128d31", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "AMeta __prepare__ Person () {}\n", - "AMeta.__new__ name='Person', bases=(), classdict={'added_attr_a': 2, 'added_attr_b': 99, '__module__': '__main__', '__qualname__': 'Person', '__firstlineno__': 1, 'age': 99, '__new__': , '__init__': , '__static_attributes__': ('name',), '__classcell__': }, kwargs={}\n", - "AMeta __new__ \n", - "AMeta __init__ Person () {'added_attr_a': 2, 'added_attr_b': 99, '__module__': '__main__', '__qualname__': 'Person', '__firstlineno__': 1, 'age': 99, '__new__': , '__init__': , '__static_attributes__': ('name',), '__classcell__': }\n" - ] - } - ], - "source": [ - "class Person(metaclass=AMeta):\n", - " age = 99\n", - "\n", - " def __new__(cls, *args, **kwargs):\n", - " print(f\"Person.__new__ {cls=}, {args=}, {kwargs=}\")\n", - " return super().__new__(cls)\n", - "\n", - " def __init__(self, name):\n", - " print(f\"Person.__init__ {name=}\")\n", - " self.name = name" - ] - }, - { - "cell_type": "code", - "execution_count": 64, - "id": "cbfa6c36-6c00-4c64-9e59-caa4c24f91dd", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'added_attr_a': 2,\n", - " 'added_attr_b': 99,\n", - " '__module__': '__main__',\n", - " '__firstlineno__': 1,\n", - " 'age': 99,\n", - " '__new__': )>,\n", - " '__init__': ,\n", - " '__static_attributes__': ('name',),\n", - " '__dict__': ,\n", - " '__weakref__': ,\n", - " '__doc__': None})" - ] - }, - "execution_count": 64, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Person.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 65, - "id": "6d596593-7f02-482f-a784-975d586f84bb", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "AMeta __call__ ('Steve',) {}\n", - "Person.__new__ cls=, args=('Steve',), kwargs={}\n", - "Person.__init__ name='Steve'\n" - ] - } - ], - "source": [ - "steve = Person(\"Steve\")" - ] - }, - { - "cell_type": "code", - "execution_count": 67, - "id": "4ce5ac22-0d1e-4db0-85f9-454f6519e80e", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'name': 'Steve'}" - ] - }, - "execution_count": 67, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 68, - "id": "f503a867-cf75-4676-9c9d-f4768db221d8", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "<__main__.Person at 0x110bd0590>" - ] - }, - "execution_count": 68, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve" - ] - }, - { - "cell_type": "code", - "execution_count": 69, - "id": "d90ba9fd-290a-4346-8067-ca65f47876b6", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "'Person' object is not callable", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[69]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[43msteve\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n", - "\u001b[31mTypeError\u001b[39m: 'Person' object is not callable" - ] - } - ], - "source": [ - "steve()" - ] - }, - { - "cell_type": "code", - "execution_count": 70, - "id": "24615807-9e94-412c-a571-96a6f0efb037", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "AMeta __prepare__ Person () {}\n", - "AMeta.__new__ name='Person', bases=(), classdict={'added_attr_a': 2, 'added_attr_b': 99, '__module__': '__main__', '__qualname__': 'Person', '__firstlineno__': 1, 'age': 99, '__new__': , '__init__': , '__call__': , '__static_attributes__': ('name',), '__classcell__': }, kwargs={}\n", - "AMeta __new__ \n", - "AMeta __init__ Person () {'added_attr_a': 2, 'added_attr_b': 99, '__module__': '__main__', '__qualname__': 'Person', '__firstlineno__': 1, 'age': 99, '__new__': , '__init__': , '__call__': , '__static_attributes__': ('name',), '__classcell__': }\n" - ] - } - ], - "source": [ - "class Person(metaclass=AMeta):\n", - " age = 99\n", - "\n", - " def __new__(cls, *args, **kwargs):\n", - " print(f\"Person.__new__ {cls=}, {args=}, {kwargs=}\")\n", - " return super().__new__(cls)\n", - "\n", - " def __init__(self, name):\n", - " print(f\"Person.__init__ {name=}\")\n", - " self.name = name\n", - "\n", - " def __call__(self):\n", - " print(f\"Person.__call__\")" - ] - }, - { - "cell_type": "code", - "execution_count": 71, - "id": "3a4b947c-ade1-46e2-a0fc-4e07b00f52c4", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "AMeta __call__ ('Steve',) {}\n", - "Person.__new__ cls=, args=('Steve',), kwargs={}\n", - "Person.__init__ name='Steve'\n" - ] - } - ], - "source": [ - "steve = Person(\"Steve\")" - ] - }, - { - "cell_type": "code", - "execution_count": 72, - "id": "68efd54c-b610-43cd-8542-416c3bd2ddcd", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person.__call__\n" - ] - } - ], - "source": [ - "steve()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4e07640f-74b5-47d5-b098-6d82d13f6c4b", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "46c8afa5-84ed-43bc-a3ef-995e52d3498e", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 73, - "id": "d3b471e4-15a8-4943-a00e-4127e2b9e77e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "AMeta.__new__ name='Student', bases=(,), classdict={'school': 'HSE'}, kwargs={}\n", - "AMeta __new__ \n", - "AMeta __init__ Student (,) {'school': 'HSE'}\n" - ] - } - ], - "source": [ - "Student = AMeta(\"Student\", (Person,), {\"school\": \"HSE\"})" - ] - }, - { - "cell_type": "code", - "execution_count": 74, - "id": "fe4c9fff-a7d1-440c-8c88-291f55cd16ce", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "AMeta __call__ ('Woz',) {}\n", - "Person.__new__ cls=, args=('Woz',), kwargs={}\n", - "Person.__init__ name='Woz'\n" - ] - } - ], - "source": [ - "woz = Student(\"Woz\")" - ] - }, - { - "cell_type": "code", - "execution_count": 75, - "id": "0ab1ca8d-da66-4338-b8dc-7bf1884d192b", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person.__call__\n" - ] - } - ], - "source": [ - "woz()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "302ce088-ce51-4ed1-9680-38f40e4c3c13", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 83, - "id": "4b9811a1-ebad-49d6-9b7c-16f4dbf4e41e", - "metadata": {}, - "outputs": [], - "source": [ - "class Singleton:\n", - " _instance = None\n", - " \n", - " def __new__(cls, *args, **kwargs):\n", - " print(\"Singleton.__new__\", cls)\n", - " if cls._instance is None:\n", - " cls._instance = super().__new__(cls)\n", - " return cls._instance\n", - "\n", - "\n", - "class Animal(Singleton):\n", - " def __init__(self, name):\n", - " print(f\"Animal.__init__, {name=}\")\n", - " self.name = name" - ] - }, - { - "cell_type": "code", - "execution_count": 84, - "id": "6cd39129-8f87-4a43-9b77-a84a33ebd6ad", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'__module__': '__main__',\n", - " '__firstlineno__': 11,\n", - " '__init__': ,\n", - " '__static_attributes__': ('name',),\n", - " '__doc__': None})" - ] - }, - "execution_count": 84, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Animal.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 85, - "id": "c5850a60-3370-49ea-976b-6e0c9b48298e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Singleton.__new__ \n", - "Animal.__init__, name='tiger'\n" - ] - } - ], - "source": [ - "tiger = Animal(\"tiger\")" - ] - }, - { - "cell_type": "code", - "execution_count": 87, - "id": "be9ba441-d429-4588-bb18-33e95e6c2a49", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'name': 'tiger'}" - ] - }, - "execution_count": 87, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "tiger.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 88, - "id": "85181d6e-26ad-4fdd-bda8-cca66d0f4490", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'__module__': '__main__',\n", - " '__firstlineno__': 11,\n", - " '__init__': ,\n", - " '__static_attributes__': ('name',),\n", - " '__doc__': None,\n", - " '_instance': <__main__.Animal at 0x110bd17f0>})" - ] - }, - "execution_count": 88, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Animal.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 89, - "id": "269b3a32-4a3a-4e88-adc4-3a46c8179324", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Singleton.__new__ \n", - "Animal.__init__, name='zebra'\n" - ] - } - ], - "source": [ - "zebra = Animal(\"zebra\")" - ] - }, - { - "cell_type": "code", - "execution_count": 90, - "id": "afb5225e-de3d-4723-b332-3c52fc249c19", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 90, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "tiger is zebra" - ] - }, - { - "cell_type": "code", - "execution_count": 91, - "id": "91875158-23d4-44b4-80e5-c11cca730f03", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "('zebra', 'zebra')" - ] - }, - "execution_count": 91, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "zebra.name, tiger.name" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9041b8f6-a1bb-4f65-8ce1-63ab21c1fcf1", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8e4748e0-81c1-4123-bcb8-93aba7b2083f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 92, - "id": "efcf5c99-76f2-4f99-b4bb-a2949dc45112", - "metadata": {}, - "outputs": [], - "source": [ - "class SingletonMeta(type):\n", - " _instances = {}\n", - "\n", - " def __call__(cls, *args, **kwargs):\n", - " print(\"SingletonMeta __call__\", cls, args, kwargs)\n", - "\n", - " if cls not in cls._instances:\n", - " cls._instances[cls] = super().__call__(*args, **kwargs)\n", - "\n", - " return cls._instances[cls]\n", - "\n", - "\n", - "class DbConnector(metaclass=SingletonMeta):\n", - " def __init__(self, creds):\n", - " print(f\"DbConnector.__init__, {creds=}\")\n", - " self.creds = creds" - ] - }, - { - "cell_type": "code", - "execution_count": 93, - "id": "a2a8b57e-1a87-4697-bfb2-16857ae0a930", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "SingletonMeta __call__ ('clients',) {}\n", - "DbConnector.__init__, creds='clients'\n" - ] - } - ], - "source": [ - "sqlite = DbConnector(\"clients\")" - ] - }, - { - "cell_type": "code", - "execution_count": 95, - "id": "cf8cd6a4-a2c1-4f4c-8796-49fbc1ec38ca", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'creds': 'clients'}" - ] - }, - "execution_count": 95, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "sqlite.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 96, - "id": "c591e0ea-0d83-40e0-9380-403a4397b8d7", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'__module__': '__main__',\n", - " '__firstlineno__': 13,\n", - " '__init__': ,\n", - " '__static_attributes__': ('creds',),\n", - " '__dict__': ,\n", - " '__weakref__': ,\n", - " '__doc__': None})" - ] - }, - "execution_count": 96, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "DbConnector.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 97, - "id": "6fedb53a-e337-4b6e-a51f-1df84f71a919", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{__main__.DbConnector: <__main__.DbConnector at 0x110bd27b0>}" - ] - }, - "execution_count": 97, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "SingletonMeta._instances" - ] - }, - { - "cell_type": "code", - "execution_count": 98, - "id": "5d37c7c9-9147-49ba-b6da-f6f6a74fa456", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "SingletonMeta __call__ ('persons',) {}\n" - ] - } - ], - "source": [ - "mysql = DbConnector(\"persons\")" - ] - }, - { - "cell_type": "code", - "execution_count": 99, - "id": "9978e298-1402-4872-82a2-6d384b25a85a", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 99, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "mysql is sqlite" - ] - }, - { - "cell_type": "code", - "execution_count": 100, - "id": "518840ba-4c02-4350-9a65-5330a676e26c", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "('clients', 'clients')" - ] - }, - "execution_count": 100, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "mysql.creds, sqlite.creds" - ] - }, - { - "cell_type": "code", - "execution_count": 101, - "id": "dbc2996e-c95d-4761-9891-ec73ee917f67", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{__main__.DbConnector: <__main__.DbConnector at 0x110bd27b0>}" - ] - }, - "execution_count": 101, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "SingletonMeta._instances" - ] - }, - { - "cell_type": "code", - "execution_count": 102, - "id": "086d42ae-a309-4a6c-8790-e4d10e520a87", - "metadata": {}, - "outputs": [], - "source": [ - "class NetConnector(metaclass=SingletonMeta):\n", - " pass" - ] - }, - { - "cell_type": "code", - "execution_count": 103, - "id": "890ac441-38ad-45d6-8709-1a11a1a1b3dd", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "SingletonMeta __call__ () {}\n" - ] - } - ], - "source": [ - "net = NetConnector()" - ] - }, - { - "cell_type": "code", - "execution_count": 104, - "id": "fae85f67-42dc-4345-926d-da367f7eb043", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{__main__.DbConnector: <__main__.DbConnector at 0x110bd27b0>,\n", - " __main__.NetConnector: <__main__.NetConnector at 0x110bd23c0>}" - ] - }, - "execution_count": 104, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "SingletonMeta._instances" - ] - }, - { - "cell_type": "code", - "execution_count": 105, - "id": "878279e0-5c9f-479d-a4f9-0be678e176e5", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "SingletonMeta __call__ () {}\n" - ] - } - ], - "source": [ - "net1 = NetConnector()" - ] - }, - { - "cell_type": "code", - "execution_count": 106, - "id": "197625aa-4943-441e-8299-a5827b9e3e5f", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 106, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "net is net1" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1937e69e-3403-457f-93a9-40f0fbe304de", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "49bb3998-472f-4cec-90b6-cd9ead0191f1", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e1962054-3676-4752-814e-978361b5f18c", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 107, - "id": "be974d91-b353-4f77-bdbb-a155fa361fe8", - "metadata": {}, - "outputs": [], - "source": [ - "from abc import ABC, ABCMeta, abstractmethod" - ] - }, - { - "cell_type": "code", - "execution_count": 115, - "id": "79348fe4-e156-44fb-a23f-6d2574b22450", - "metadata": {}, - "outputs": [], - "source": [ - "class Person(ABC):\n", - " @abstractmethod\n", - " def eat(self, food):\n", - " print(f\"Person.eat {food=}\")\n", - " return \"tasty\"\n", - "\n", - " @abstractmethod\n", - " def sleep(self):\n", - " return NotImplemented\n", - "\n", - " def study(self, food):\n", - " print(f\"Person.study {self=} {food=}\")\n", - " print(self.eat(food))\n", - " self.sleep()" - ] - }, - { - "cell_type": "code", - "execution_count": 116, - "id": "97bf27cc-130f-4422-9d55-372fdaafaad4", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "Can't instantiate abstract class Person without an implementation for abstract methods 'eat', 'sleep'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[116]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m pers = \u001b[43mPerson\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n", - "\u001b[31mTypeError\u001b[39m: Can't instantiate abstract class Person without an implementation for abstract methods 'eat', 'sleep'" - ] - } - ], - "source": [ - "pers = Person()" - ] - }, - { - "cell_type": "code", - "execution_count": 117, - "id": "d4f026b1-077b-4001-a87f-154d9a7737ab", - "metadata": {}, - "outputs": [], - "source": [ - "class Student(Person):\n", - " def sleep(self):\n", - " print(f\"Student.sleep\")\n", - "\n", - "\n", - "class HungryStudent(Student):\n", - " def eat(self, food):\n", - " print(f\"HungryStudent.eat {food=}\")\n", - " return super().eat(food)" - ] - }, - { - "cell_type": "code", - "execution_count": 111, - "id": "f1b03b82-aff4-44bb-8fa5-9b48e54b0b27", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "Can't instantiate abstract class Student without an implementation for abstract method 'eat'", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mTypeError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[111]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m stud = \u001b[43mStudent\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n", - "\u001b[31mTypeError\u001b[39m: Can't instantiate abstract class Student without an implementation for abstract method 'eat'" - ] - } - ], - "source": [ - "stud = Student()" - ] - }, - { - "cell_type": "code", - "execution_count": 118, - "id": "087ee0e1-2297-40ec-8183-de7b0412b1b7", - "metadata": {}, - "outputs": [], - "source": [ - "steve = HungryStudent()" - ] - }, - { - "cell_type": "code", - "execution_count": 119, - "id": "1fcdb1e9-91a1-4a75-86c0-4237974a68fd", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "HungryStudent.eat food='apple'\n", - "Person.eat food='apple'\n" - ] - }, - { - "data": { - "text/plain": [ - "'tasty'" - ] - }, - "execution_count": 119, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "steve.eat(\"apple\")" - ] - }, - { - "cell_type": "code", - "execution_count": 120, - "id": "e7514dde-592e-4248-a031-56d582275fb3", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Person.study self=<__main__.HungryStudent object at 0x110bd1be0> food='pear'\n", - "HungryStudent.eat food='pear'\n", - "Person.eat food='pear'\n", - "tasty\n", - "Student.sleep\n" - ] - } - ], - "source": [ - "steve.study(\"pear\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "20576279-7a77-4d13-866b-a35c56e2249e", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 121, - "id": "97e941fb-659f-439f-abe3-095c51933456", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'__module__': '__main__',\n", - " '__firstlineno__': 6,\n", - " 'eat': ,\n", - " '__static_attributes__': (),\n", - " '__doc__': None,\n", - " '__abstractmethods__': frozenset(),\n", - " '_abc_impl': <_abc._abc_data at 0x111066980>})" - ] - }, - "execution_count": 121, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "HungryStudent.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 122, - "id": "f2b5f27f-cf8e-4ce6-900b-b0562b75ddbe", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "mappingproxy({'__module__': '__main__',\n", - " '__firstlineno__': 1,\n", - " 'eat': ,\n", - " 'sleep': ,\n", - " 'study': ,\n", - " '__static_attributes__': (),\n", - " '__dict__': ,\n", - " '__weakref__': ,\n", - " '__doc__': None,\n", - " '__abstractmethods__': frozenset({'eat', 'sleep'}),\n", - " '_abc_impl': <_abc._abc_data at 0x11163bf00>})" - ] - }, - "execution_count": 122, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Person.__dict__" - ] - }, - { - "cell_type": "code", - "execution_count": 123, - "id": "6c59db53-551a-4300-955c-da7cab441d77", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(True, False)" - ] - }, - "execution_count": 123, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(steve, Person), isinstance([1, 2, 3], Person)" - ] - }, - { - "cell_type": "code", - "execution_count": 124, - "id": "96f9173d-f1dd-4823-bdb4-504710a1de47", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "list" - ] - }, - "execution_count": 124, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Person.register(list)" - ] - }, - { - "cell_type": "code", - "execution_count": 125, - "id": "a8ab8c5e-21c4-416a-8e45-5dc33f27abd9", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(True, True)" - ] - }, - "execution_count": 125, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(steve, Person), isinstance([1, 2, 3], Person)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "12b6b591-7a36-4557-a9a9-8647a4c92ec9", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "86066b00-a113-4567-9baa-e867a85fbed9", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 129, - "id": "6bc2a76b-60f0-4cb5-9c50-ac280d8346c3", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Predictable.hook cls=, C=\n", - "Predictable.hook cls=, C=\n", - "True False\n" - ] - } - ], - "source": [ - "class Predictable(metaclass=ABCMeta):\n", - " @abstractmethod\n", - " def predict(self):\n", - " pass\n", - "\n", - " @classmethod\n", - " def __subclasshook__(cls, C):\n", - " print(f\"Predictable.hook {cls=}, {C=}\")\n", - "\n", - " if cls is not Predictable:\n", - " return NotImplemented\n", - "\n", - " name = \"predict\"\n", - " for class_ in C.__mro__:\n", - " if name in class_.__dict__ and callable(class_.__dict__[name]):\n", - " return True\n", - "\n", - " return NotImplemented\n", - "\n", - "\n", - "class TreeModel:\n", - " def predict(self):\n", - " pass\n", - "\n", - "\n", - "class TrafficLight:\n", - " predict = \"green\"\n", - "\n", - "\n", - "tree = TreeModel()\n", - "traffic = TrafficLight()\n", - "\n", - "print(\n", - " isinstance(tree, (Predictable, int, str)), # issubclass(tree.__class__, Predictable)\n", - " isinstance(traffic, (Predictable, int, str)),\n", - ")" - ] - }, - { - "cell_type": "code", - "execution_count": 130, - "id": "fc5ff98f-75ec-408c-99fc-a56c83430825", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "True False\n" - ] - } - ], - "source": [ - "print(\n", - " isinstance(tree, Predictable),\n", - " isinstance(traffic, Predictable),\n", - ")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e3bffae9-fc76-4c50-be39-f9b4a1b52e1f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "729b8183-17e8-415f-83f4-24154194d94a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d606859f-623a-4e3a-b2ca-2bc4e9a9d45a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 134, - "id": "6393340b-609f-43b5-b154-65302910a254", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Predictable.hook cls=, C=\n", - "Predictable.hook cls=, C=\n", - "TrainPredictable.hook cls=, C=\n", - "Predictable.hook cls=, C=\n", - "TrainPredictable.hook cls=, C=\n", - "TrainPredictable.hook cls=, C=\n", - "True False True False False True\n" - ] - } - ], - "source": [ - "class Predictable(metaclass=ABCMeta):\n", - " @abstractmethod\n", - " def predict(self):\n", - " pass\n", - "\n", - " @classmethod\n", - " def __subclasshook__(cls, C):\n", - " print(f\"Predictable.hook {cls=}, {C=}\")\n", - "\n", - " if cls is not Predictable:\n", - " return NotImplemented\n", - "\n", - " name = \"predict\"\n", - " for class_ in C.__mro__:\n", - " if name in class_.__dict__ and callable(class_.__dict__[name]):\n", - " return True\n", - "\n", - " return NotImplemented\n", - "\n", - "\n", - "class TrainPredictable(Predictable):\n", - " @abstractmethod\n", - " def train(self):\n", - " pass\n", - "\n", - " @classmethod\n", - " def __subclasshook__(cls, C):\n", - " print(f\"TrainPredictable.hook {cls=}, {C=}\")\n", - "\n", - " if cls is not TrainPredictable:\n", - " return NotImplemented\n", - "\n", - " for name in (\"predict\", \"train\"):\n", - " for class_ in C.__mro__:\n", - " if name in class_.__dict__ and callable(class_.__dict__[name]):\n", - " break\n", - " else:\n", - " return NotImplemented\n", - "\n", - " return True\n", - "\n", - "\n", - "class TreeModel:\n", - " def predict(self):\n", - " pass\n", - "\n", - "\n", - "class RandomForest(TreeModel):\n", - " def train(self):\n", - " pass\n", - "\n", - "\n", - "class TrafficLight:\n", - " predict = \"green\"\n", - "\n", - "\n", - "tree = TreeModel()\n", - "traffic = TrafficLight()\n", - "forest = RandomForest()\n", - "\n", - "print(\n", - " isinstance(tree, Predictable),\n", - " isinstance(traffic, Predictable),\n", - " isinstance(forest, Predictable),\n", - " isinstance(tree, TrainPredictable),\n", - " isinstance(traffic, TrainPredictable),\n", - " isinstance(forest, TrainPredictable),\n", - ")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "abb0760e-982f-4561-b397-5a9477f439f5", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 137, - "id": "43d8b4bd-31b2-49be-a73a-0fa3c8434e27", - "metadata": {}, - "outputs": [], - "source": [ - "import collections.abc as abc" - ] - }, - { - "cell_type": "code", - "execution_count": 138, - "id": "2045345d-002e-4fee-bead-d40375bb4dff", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 138, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(\"123\", abc.Hashable)" - ] - }, - { - "cell_type": "code", - "execution_count": 139, - "id": "1d01f1dc-b767-409d-a140-ec7eb4801d31", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "False" - ] - }, - "execution_count": 139, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance({}, abc.Hashable)" - ] - }, - { - "cell_type": "code", - "execution_count": 140, - "id": "d8b6f800-fc2f-48b0-a337-c28a5258e96b", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 140, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(Person, abc.Callable)" - ] - }, - { - "cell_type": "code", - "execution_count": 141, - "id": "113f322d-6df4-4a2b-a20e-0e4350af8db8", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 141, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "callable(Person)" - ] - }, - { - "cell_type": "code", - "execution_count": 145, - "id": "3ea90888-85f5-4a96-9b0b-a7615fceb6b3", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(True, False)" - ] - }, - "execution_count": 145, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance([], abc.Iterable), isinstance(list, abc.Iterable)" - ] - }, - { - "cell_type": "code", - "execution_count": 144, - "id": "27ac67ad-0521-4950-9559-8e432b2a2008", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(False, False)" - ] - }, - "execution_count": 144, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(Person, abc.Iterable), isinstance(HungryStudent(), abc.Iterable)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "842c801e-2688-471e-b125-2fcafdf1296d", - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.13.2" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/lesson-05/homework.md b/lesson-05/homework.md deleted file mode 100644 index 9197adf..0000000 --- a/lesson-05/homework.md +++ /dev/null @@ -1,48 +0,0 @@ -# Домашнее задание #05 (стандартная библиотека) - -### 1. LRU-кэш -Интерфейс: - -```py - class LRUCache: - - def __init__(self, limit=42): - pass - - def get(self, key): - pass - - def set(self, key, value): - pass - - - cache = LRUCache(2) - - cache.set("k1", "val1") - cache.set("k2", "val2") - - assert cache.get("k3") is None - assert cache.get("k2") == "val2" - assert cache.get("k1") == "val1" - - cache.set("k3", "val3") - - assert cache.get("k3") == "val3" - assert cache.get("k2") is None - assert cache.get("k1") == "val1" - - - Если удобнее, get/set можно сделать по аналогии с dict: - cache["k1"] = "val1" - print(cache["k3"]) -``` - -Сложность решения по времени в среднем должна быть константной O(1). -Реализация любым способом без использования OrderedDict. - -### 2. Тесты в отдельном модуле - -### 3. Зеленый пайплайн в репе -Обязательно: тесты, покрытие, flake8, pylint. -Опционально можно добавить другие инструменты, например, mypy и black. -Покрытие тестов должно составлять не менее 90%. diff --git a/lesson-05/lesson-05.pdf b/lesson-05/lesson-05.pdf deleted file mode 100644 index a7527d6..0000000 Binary files a/lesson-05/lesson-05.pdf and /dev/null differ