python - everjs78/study GitHub Wiki

Venv

  • ์ƒˆ ๊ฐ€์ƒํ™˜๊ฒฝ ์ƒ์„ฑ
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

list comprehension

  • [ 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

  • closure๋Š” func.closure ์— tuple๋กœ ์ €์žฅ

class

  • 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๊ณผ ๋™์ผ

Method

    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))

magic method

  • reference
  • ์šฉ๋„
    • ์ƒ์„ฑ์ž
    • operator overloading
  • example
      list(map(func, *iterables)) => mapobj.list()๊ฐ€ ํ˜ธ์ถœ ๋œ๋‹ค.
      
  • list
    • bases : base class
    • str : print(myobj) ์™€ ๊ฐ™์€ ๊ฒฝ์šฐ string์œผ๋กœ ์ถœ๋ ฅ
    • lt
    • add

performance ์ธก์ •

  • 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)
      
  • ๋”์—„๋ฐ€ํ•œ ์ธก์ •

Decorator

  • 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)
  • 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
    • _ + ์†Œ๋ฌธ์ž + _ ...
  • ์ƒ์ˆ˜
    • ๋Œ€๋ฌธ์ž + _
โš ๏ธ **GitHub.com Fallback** โš ๏ธ