python/응용
-
python MixInpython/응용 2024. 1. 31. 17:07
scala 의 trait mixin 과 비슷한 것 같다. 상속을 통해 공통으로 사용할 member, method 를 클래스에 추가함? 예제 코드 class ToDictMixin: def to_dict(self): return {key: value for key, value in self.__dict__.items()} class MyClass(ToDictMixin, BaseClass): pass 다중 상속일 경우 Q: Under multiple inheritances, if two parent classes have the same methods or attributes, what will happen? A: If two parent classes have the same method or attribu..
-
functools.singledispatch 로 typeclass 흉내 내기python/응용 2024. 1. 24. 18:10
https://docs.python.org/3/library/functools.html#functools.singledispatch https://news.ycombinator.com/item?id=22682219 functools.singledispatch 를 이용해 typeclass 처럼 만들어 보자 코드 import dataclasses import functools import math from typing import Any @dataclasses.dataclass class Circle: radius: float @dataclasses.dataclass class Rectangle: width: float height: float @functools.singledispatch def area(..
-
Coroutine yield 의 동작 이해python/응용 2023. 12. 13. 19:37
동작 yield 는 기본 적으로 다음과 같은 순서로 동작한다. 값을 리턴한다. (즉시) 입력 값을 받기 위해 대기 한다. 최초 next() 나 send(None) 호출로 coroutine 을 시작한다. 처음 만나는 yield 도 위의 설명대로 동작한다. 코드 def simple_coroutine(a): print(f"-> Started: {a=}") b = yield a print(f"-> Received: {b=}") c = yield a + b print(f"-> Received: {c=}") my_coro = simple_coroutine(14) next(my_coro) # -> Started: a=14 # 14 my_coro.send(28) # -> Received: b=28 # 42 my_cor..
-
yield 활용 2python/응용 2023. 11. 15. 11:22
개선 전 for row in range(height): for col in range(width): value = spreadsheet.get_value(col, row) do_something(value) if this_is_my_value(value): break # ??? 이중 루프를 벗어날 수 없다. Exception 으로 처리 ??? 개선 후 def range_2d(width, heigth): for y in range(height): for x in range(width): yield x, y for col, row in range_2d(widht, height): value = spreadsheet.get_value(col, row) do_something(value) if this_is_m..
-
yield 활용 1python/응용 2023. 11. 15. 11:14
개선 전 f = open("my_config.ini") for line in f: line = line.strip() if line.startswith('#'): # A comment line, skip it continue if not line: # A blank line, skip it continue do_something(line) 개선 후 f = open("my_config.ini") def interesting_lines(f): for line in f: line = line.strip() if line.startswith('#'): continue if not line: continue yield line with open("my_config.ini") as f: for line in int..
-
Decorators with parameterspython/응용 2023. 10. 17. 17:17
https://stackoverflow.com/a/25827070 Transleates decorator without parameters @decorator def foo(*args, **kwargs): pass translates to foo = decorator(foo) Transleates decorator with parameters @decorator_with_args(arg) def foo(*args, **kwargs): pass translates to foo = decorator_with_args(arg)(foo) decorator_with_args(arg) 은 function 을 파라미터로 받는 함수(decorator without parameters)가 되어야 한다. 코드 import..
-
type hints Self typepython/응용 2023. 10. 17. 16:47
https://stackoverflow.com/a/33533514 How do I type hint a method with the type of the enclosing class? I have the following code in Python 3: class Position: def __init__(self, x: int, y: int): self.x = x self.y = y def __add__(self, other: Position) -> Position: stackoverflow.com from __future__ import annotations from dataclasses import dataclass @dataclass class Vector: x: float y: float def ..
-
Tipspython/응용 2023. 8. 20. 18:58
https://betterprogramming.pub/87-lesser-known-python-features-635180720a29 87 Lesser-known Python Features This post is for people who use Python daily, but have never actually sat down and read through all the documentation. betterprogramming.pub str.endswith(), isinstance() take a tuple if filename.endswith((".csv", ".xls", ".xlsx")) # Do something spreadsheety assert isinstance(7, (float, int..