본문 바로가기

728x90
반응형

Python

(100)
Python: class inheritance MRO, super # method resolution order # super # 상속 순서 # 부모 클래스 # 초기화 Python에서는 class에서 상속받을 시, method가 겹칠 때, 어떤 순서로 method를 적용시킬지를 정해놓았는데 이를 MRO(Method Resolution Order)이라 한다. __mro__ CLASS.__mro__ 로 순서를 확인할 수 있다. class A: pass class B: pass class C(A,B): pass print(C.__mro__) # (, , , ) 위의 결과를 보면 C, A, B 순으로 되어 있는 것을 확인할 수 있다. * 다양한 상속 환경에서 method 실행해보기 class A: def method(self): print('from A') def parent_method(self): print('parent from A') class B: def method..
Python: [False] and [True] # falsy values in python # [False] or [True] # bool [False] and [True]의 결과는 무엇일까? False? True? 답은 [True] and 연산은 False 또는 False로 간주되는 값이 나올때까지 다음과 비교한다. False가 나오지 않는다면 마지막 값을 리턴 [False]는 boolean 타입이 아니라 리스트 타입이다. 따라서 False가 아니라 그다음 [True]를 비교한다. [True] 역시 list이다. 그 뒤에 확인할 요소가 없으므로 [True]를 반환 추가적인 예시 print([False] and [True]) print([False] and [False]) print([True] and False and True) print([True] and [] and False) # [True] # [False] # False # []..
멀티프로세싱, 멀티스레딩 이해하기 with Python CPU (central processing unit) - 명령어를 실행하는 연산 장치 - 메모리에서 데이터를 읽고 쓰는 등의 계산 작업에 집중 메인 메모리 - 프로세스가 CPU 에서 실행되기 위해 대기하는 곳 IO (input/output) - 파일을 읽고 쓰거나 - 네트워크의 어딘가와 데이터를 주고 받는 것 - 입출력 장치와 데이터를 주거나 받는 것 - 하드 디스크, 네트워크 카드, 그래픽 카드 등과 관련된 하드웨어 장치가 처리 (CPU가 하지 않음) 프로그램 - 컴퓨터가 실행할 수 있는 명령어들의 집합 프로세스 - 컴퓨터에서 실행중인 프로그램 - 각각의 프로세스는 독립된 메모리 공간을 할당 받음 - 명령어들과 데이터를 가짐 - 프로세스는 한 개 이상의 스레드를 가질 수 있다. 스레드 - 프로세스 내에..
Python: Generator # 제너레이터 # yield Generator - 이터레이터를 생성해주는 함수 - yield의 개수만큼 이터레이터에서 값을 꺼낼 수 있다. * generator를 통해 생성된 이터레이터는 하나씩 값을 꺼낼 수 있다. (yield 개수 만큼) -> 부분적으로 여러번 yield를 통해 값을 바깥으로 전달 가능하기 때문에 특정 결과를 순차적으로 얻을 때, 통으로 결과를 기다릴 필요 없이 부분적으로 확인 가능 (예시 코드는 아래) * 모든 값을 생성하는 것이 아니라 yield에 걸리는 값만 생성해서 메모리에 올리므로 메모리를 효율적으로 사용 가능 (이터레이터는 값을 미리 만들지 않고 값이 필요한 시점에 값을 만드는 방식) 예시 - return을 사용하는 일반 함수 예시 import time def return_number(): num_li..
Python: Deep copy , Shallow copy, # mutable, immutable # 깊은 복사, 얕은 복사 mutable vs immutable Python의 자료 형 중에 mutable 한 자료형과 immutable한 자료형이 있다. mutable은 값이 변할수 있는 자료형 immutable은 값이 변할수 없는 자료형 의미 immutable 자료형: int, float, str, bool, tuple + complex, frozenset, bytes mutable 자료형: list, set, dict + deque, bytearray, array.array * immutable 여부 확인해보기 특정 index를 잡아서 새로 값 할당시 아래와 같은 TypeError 발생시 immutable임을 확인 가능 a = bytes([1, 2, 3]) print(a) a[0] = 1 # TypeError: 'bytes'..
Python: del vs slice 성능 비교 from timeit import Timer s1 = ['a', 'b', 'c'] * 50000 s2 = ['a', 'b', 'c'] * 50000 t1 = Timer('del s1[10000:10003]', 'from __main__ import s1') t2 = Timer('s2[10000:10003]', 'from __main__ import s2') r1 = t1.timeit(number=10000000) r2 = t2.timeit(number=10000000) print("@@@@@") print(r1) print(r2) ######################################################## t1 = Timer('del s1[-4:]', 'from __main__ ..
FastAPI description FastAPI is a Python class that provides all the functionality for your API FastAPI is a class that inherits directly from Starlette. You can use all the Starlette functionality with FastAPI too. (https://fastapi.tiangolo.com/tutorial/first-steps) Pydantic All the data validation is performed under the hood by Pydantic, so you get all the benefits from it. And you know you are in good hands. Pyda..
Python: Union[bool, None] = None # Type hint Python Type hint from typing import Union class Item: name: str price: float is_offer: Union[bool, None] = None 1) is_offer: Union [bool, None] is_offer의 type을 bool이나 None으로 받겠다 2) is_offer: Union[bool, None] = None is_offer의 default type은 None으로 지정

728x90
반응형