Post

(python) 사용하면 좋은 패턴들

데이터 클래스는? @dataclass

docs.python.org/ko/3/library/dataclasses.html

다형성을 쓰고 싶다면? abc 클래스

  • python에 interface는 없지만 abstract base class가 있다.
  • https://docs.python.org/ko/3/library/abc.html
  • 근데 메서드 명만 같으면 되고, 파라미터는 강제하지 않음. 근데 어차피 다형성 쓸거라면 파라미터도 맞춰주어야 한다.

Python Singleton

https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python

wikidocs.net/3693

doctest : docstring에 간단히 명시해서 로직 테스트 가능

https://docs.python.org/ko/3/library/doctest.html

defaultdict : KeyError가 아니라 기본값으로 초기화해주는 딕셔너리
1
2
3
4
5
from collections import defaultdict

d\_dict = defaultdict(int) # type 지정 필요

dotdict (.으로 접근할 수 있는 딕셔너리)

1
2
3
4
class dotdict(dict):
def \_\_getattr\_\_(self, name):
return self[name]

https://stackoverflow.com/questions/2352181/how-to-use-a-dot-to-access-members-of-dictionary

SimpleNamespace , object_hook

https://stackoverflow.com/questions/6578986/how-to-convert-json-data-into-a-python-object

클래스 메서드에서 어떤 값을 초기 한 번만 계산하고 이후 호출에서는 단순히 반환만 하고 싶을 때

* property에 사용하면 좋다. 2018/08/07 - [Coding Syntax/Python] - [python] @property와 property() 클래스

1
2
3
4
5
6
class T:
def getData(self):
if hasattr(self, "var"):
self.var = 3
return self.var

2019/02/04 - [Coding Syntax/Python] - 파이썬에는 확장 함수가 없다. 어떤 클래스에 추가 기능이 필요한 경우.

파이썬에서 클로저 사용하기

1
2
3
4
5
def makeMultiplier(operand):
def multiplier(arg):
return arg \* operand
return multiplier

1
2
3
4
>>> multi2 = makeMultiplier(2)
>>> multi2(4)
8

@dump 데커레이터

1
2
3
4
5
6
7
8
9
10
def dump(func):
def wrapped(\*args, \*\*kwargs):
print("func name: {}".format(func.\_\_name\_\_))
print("args     : {}".format(' '.join(map(str, args))))
print("kwargs   : {}".format(kwargs.items()))
output = func(\*args, \*\*kwargs)
print("output   : {}".format(output))
return output
return wrapped

vars() 키워드

1
2
3
4
5
6
>>> def a(a):
...     print(vars())
...
>>> a(3)
{'a': 3}

기타 팁과 메모

[python] 팁, 메모

This post is licensed under CC BY 4.0 by the author.