-
Notifications
You must be signed in to change notification settings - Fork 0
python
jaeseok.an edited this page Nov 13, 2019
·
28 revisions
- 새 가상환경 생성
python3 -m venv my-test-env
- package install
- my-test-env> 환경에서 pip install로 설치
- pip list로 확인
- pip로 관리
pip list
pip freeze > requirements.txt
pip install -r requirements.txt
- 가상환경 active
source ./my-test-env/bin/activate
- [ expression for item in iterable if 조건 ]
a_list = [number for number in range(1, 6) if number % 2 == 1]
>>>> a_list
[1, 3, 5]
- closure는 func.closure 에 tuple로 저장
- constructor (initializer)
- 자식 class에서 __init__호출시 자동으로 부모 __init__이 호출 안됨
class Employee(object):
def __init__(self, first, last, pay):
- namespace
- instance namespace -> class namespace -> super namespace
- class variable 은 모든 instance가 동일 값을 공유
- class static과 동일
- reference
- instance method - self 를 첫 인자로(convention)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
- class method - cls를 첫인자로(convention), @classmethod decorator를 이용
@classmethod
def ssn_constructor(cls, ssn):
front, back = ssn.split('-')
sex = back[0]
if sex == '1' or sex == '2':
year = '19' + front[:2]
else:
year = '20' + front[:2]
if (int(sex) % 2) == 0:
sex = '여성'
else:
sex = '남성'
month = front[2:4]
day = front[4:6]
return cls(year, month, day, sex)
- static method - class안에 존재하는 일반 함수 역할
@staticmethod
def is_work_day(day):
# weekday() 함수의 리턴값은
# 월: 0, 화: 1, 수: 2, 목: 3, 금: 4, 토: 5, 일: 6
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
- super() 메서드
- 상위 class의 함수 호출 가능
def show_status(self):
super(Goblin, self).show_status()
print('공격 타입: {}'.format(self.attack_type))
- reference
- 용도
- 생성자
- operator overloading
- example
list(map(func, *iterables)) => mapobj.list()가 호출 된다.
- list
- bases : base class
- str : print(myobj) 와 같은 경우 string으로 출력
- lt
- add
- time.perf_counter
import functools import time def timer(func): """Print the runtime of the decorated function""" @functools.wraps(func) def wrapper_timer(*args, **kwargs): start_time = time.perf_counter() # 1 value = func(*args, **kwargs) end_time = time.perf_counter() # 2 run_time = end_time - start_time # 3 print(f"Finished {func.__name__!r} in {run_time:.4f} secs") return value return wrapper_timer @timer def waste_some_time(num_times): for _ in range(num_times): sum([i**2 for i in range(10000)]) print(waste_some_time) waste_some_time(1000) - 더엄밀한 측정
- timeit — Measure execution time of small code snippets(https://docs.python.org/3/library/timeit.html)
- argument가 없는 기본 decorator
def decorator_repeat(func):
@functools.wraps(func)
def wrapper_repeat(*args, **kwargs):
...
return wrapper_repeat
- argument가 있는 decorator pattern
def repeat(num_times):
def decorator_repeat(func):
def wrapper_repeat(*args, **kwargs):
...
return wrapper_repeat
return decorator_repeat
...
실제예
def repeat(num_times):
def decorator_repeat(func):
@functools.wraps(func)
def wrapper_repeat(*args, **kwargs):
for _ in range(num_times):
value = func(*args, **kwargs)
return value
return wrapper_repeat
return decorator_repeat
- singleton decorator
import functools
def singleton(cls):
"""Make a class a Singleton class (only one instance)"""
@functools.wraps(cls)
def wrapper_singleton(*args, **kwargs):
if not wrapper_singleton.instance:
wrapper_singleton.instance = cls(*args, **kwargs)
return wrapper_singleton.instance
wrapper_singleton.instance = None
return wrapper_singleton
@singleton
class TheOne:
pass
- caching
import functools
from decorators import count_calls
def cache(func):
"""Keep a cache of previous function calls"""
@functools.wraps(func)
def wrapper_cache(*args, **kwargs):
cache_key = args + tuple(kwargs.items())
if cache_key not in wrapper_cache.cache:
wrapper_cache.cache[cache_key] = func(*args, **kwargs)
return wrapper_cache.cache[cache_key]
wrapper_cache.cache = dict()
return wrapper_cache
@cache
def fibonacci(num):
if num < 2:
return num
return fibonacci(num - 1) + fibonacci(num - 2)
PEP8 style guide (https://www.python.org/dev/peps/pep-0008/#introduction)
- tab = 4 spaces
- max = 79 , comments와 docstring = 72
- blacklines
- function, class = 2 line
- method = 1 link
- 소스파일 인코딩
- UTF-8 (or ASCII in Python 2)
- 이 경우 encoding 선언문은 두지 않는다.
- import
- 항상 file top
- 한 라인에는 하나의 import
- package안의 여러 module은 한 line에 import 허용
- Absolute import를 추천
- 와일드카드 import는 피한다
- '__'로 시작하는 Dunder 선언은 모든 import앞에 온다.
- 화이트스페이스
- 되도록 피한다
- ','앞에는 안쓴다.
- 스트링[앞:뒤] 인 경우 ':' 앞뒤로 다 붙이던가 다 띄운다.
- 변수 선언시 align 맞추기 위해 쓸데없는 스페이스 안쓴다.
- a = 12 + 34 처럼 우선순위가 낮으면 스페이스를 쓴다.
- 함수
def munge(input: AnyStr): ... def munge() -> PosInt: ...- keyword나 디폴트 지정시 스페이스 안씀
- trailing 컴마
FILES = [ 'setup.cfg', 'tox.ini', ] initialize(FILES, error=True, ) - comment
- multiline일때 2 space를 쓴다.
- docstring
- 모든 public modules, functions, classes, and methods에 쓴다.
- package and module
- 짧게, 소문자 + _ 로 사용
- class
- camel case
- Type
- camel case + _ 소문자도 가능
- Function , varialbe
- 소문자 + _ 로만 사용
- Private method, variable
- _ + 소문자 + _ ...
- 상수
- 대문자 + _
test