본문 바로가기

Python

(94)
[Python] Magic Method(1) 워밍업 # 참조 : https://docs.python.org/3/reference/datamodel.html#special-method-names# 클래스 안에서 정의할 수 있는 특별한(built-in) 매소드, 파이썬에 이미 정의된 함수들임.# 기본형 - 모두 클래스입니다.print(int)print(float)# # # 모든 속성 및 메소드 출력print(dir(int))print(dir(float))# ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floord..
[Python] Class(3) - Class Method, Static Method Instance method, Class method, Static method # 클래스 선언class Car(object): ''' Car Class Author : Me Date : Description : Class, Static Method, Class Method ''' # Class Variable(모든 인스턴스가 공유 가능) price_per_raise = 1.0 def __init__(self, company, details): self._company = company self._details = details def __str__(self): return 'str : {} - ..
[Python] Class(2) - self, 매직 매소드 # Chapter02-02# 파이썬 심화# 객체 지향 프로그래밍(OOP) -> 코드의 재사용, 코드 중복 방지 등# 클래스 상세 설명# 클래스 변수, 인스턴스 변수# 클래스 재 선언class Car(): # Doctring """ ~ """ """ Car Class Author : Kim Date : 2019.11.08 사용법: """ # 클래스 변수, 모든 인스턴스가 공유함. car_count = 0 # self 는 인스턴스 입니다. def __init__(self, company, details): self._company = company self._details = details Car.car_coun..
[Python] Class(1) - Basic print(car1) 과 print(car_list) 의 차이에 주의할 것, 객체를 직접출력할때와 객체를 리스트에 넣어서 출력할때 차이 있음.print(car1) - str 로 출력print(car_list) - 객체를 리스트에 넣어서 출력하면 __repr__ 로 출력 class Car(): def __init__(self, company, details): self._company = company self._details = details def __str__(self): # 매직 메소드, 간단한 사용자 레벨의 출력 return 'str : {} - {}'.format(self._company, self._details) # __str__ 함수를 ..
CPU Bound(2) - Multi-process CPU 연산 - 멀티 프로세스 from multiprocessing import current_process, Array, freeze_support, Process, Manager import time import os def cpu_bound(number, total_list): process_id = os.getpid() process_name = current_process().name # Process 정보 출력 print(f"Process ID: {process_id}, Process Name: {process_name}") total_list.append(sum(i * i for i in range(number))) def main(): numbers = [3_000_000 + x for x..
CPU Bound(1) - Single process CPU 연산 - 단일 프로세스 import time def cpu_bound(number): return sum(i * i for i in range(number)) def find_sums(numbers): result = [] for number in numbers: result.append(cpu_bound(number)) return result def main(): numbers = [3_000_000 + x for x in range(30)] # 확인 # print(numbers) start_time = time.time() total = find_sums(numbers) print() print(f"Total list : {total}") print(f"Sum : {sum(total)}") ..
[Python] I/O Bound(2) - Asyncio 통신관련 비동기 처리 import asyncio import aiohttp # import requests # 패키지는 동기방식이라서 사용불가. import time async def request_site(session, url): # 세션 확인 # print(session) # print(session.headers) async with session.get(url) as response: # status_code 동기화 문제 print("Read Contents {}, from {}, stauts:{}".format(response.content_length, url, response.status)) # print("*****Read Contents {0}, from {1}".format(respo..
[Python] I/O Bound(2) - Asyncio basic 비동기 기초 샘플 코드 동시 프로그래밍 패러다임 변화 싱글코어 -> 처리향상 미미, 저하 -> 비동기 프로그래밍 -> CPU연산, DB연동, API호출 대기 시간 늘어남 => 논블로킹으로 변환 파이썬에서 비동기 프로그래밍은 개념을 잘 잡아야 함. 파이썬 3.4에서 비동기(asyncio) 표준라이브러리 등장 import time import asyncio async def exe_calculate_async(name, n): for i in range(1, n + 1): print(f'{name} -> {i} of {n} is calculating..') # time.sleep(1) # 동기 처리, 시간비교하기 좋음 await asyncio.sleep(1) # 비동기 처리, 시간비교하기 좋음 print(f..