Python/이것저것 파이썬
-
[파이썬] str, bytes, bytearrayPython/이것저것 파이썬 2022. 8. 15. 12:25
결론: 1. bytes는 문자열(str)을 숫자(byte)로 다룹니다. 즉, bytes는 문자열(str)을 숫자(byte) 뭉치로 바꾼 것입니다. 2. 한글을 써야하는 상황에서 bytes를 직접 다룰 일은 많지 않습니다. bytes를 디코딩을 거쳐 문자열(str)로 변환한 뒤, 문자열(str)을 다루면 됩니다. 0. 미리 알아야 할 것 ASCII 코드 ASCII (American Standard Code for Information Interchange, 미국 정보 교환 표준 부호) 000(0x00)부터 127(0x7F)까지 총 128개의 부호가 사용된다. 1바이트를 구성하는 8비트(=1바이트) 중에서 7비트만 쓰도록 제정된 이유는, 나머지 1비트를 통신 에러 검출을 위한 용도로 비워두었기 때문이다. 한..
-
객체 지향....Python/이것저것 파이썬 2022. 8. 14. 00:38
반박 시 당신 말씀이 맞습니다. 붕어빵에 비유 클래스(붕어빵 틀)는 객체(붕어빵)를 찍어내기 위한 문법입니다. 클래스 : 붕어빵 틀 객체 : 붕어빵 게임에 비유 게임에는 기사, 마법사, 궁수, 사제 등 클래스(직업, 직능)가 있죠? 캐릭터를 만들 때, 클래스를 선택한 한 뒤, 이름을 붙입니다. 이 과정을 거쳐 생성된 캐릭터가 객체입니다. 클래스라는 틀로, 캐릭터라는 객체를 찍어냈다고 할 수도 있죠. 클래스: 기사, 법사, 궁수, 사제, 성기사 객체 : 생성된 캐릭터 속성과 메서드 객체 지향 프로그래밍에서 핵심은 객체겠죠? 객체란 뭘까요? 속성(데이터)과 함수(동작)를 합친 것입니다. * 클래스 내의 함수를 메서드(method)라고 합니다. 캐릭터를 생성하면, 각각의 캐릭터에 능력치 (헬스, 마나, 근접 ..
-
파이썬 비동기 연습Python/이것저것 파이썬 2022. 8. 5. 13:52
0. 먼저 이 영상을 보고 개념을.. 자바스크립트로 예를 들었지만, 개념 설명이 좋은 것 같습니다... https://www.youtube.com/watch?v=m0icCqHY39U 1. 파이썬에서의 비동기를 잘 정리한 블로그.. https://kukuta.tistory.com/345 동기 프로그래밍을 비동기 프로그래밍으로 바꾸는 과정, 이 과정에서 필요한 키워드인 async, await, asyncio.run(), asyncio.gather(), asyncio.get_event_loop(), run_in_executor() 를 모두 알려주네요. 읽기 편합니다. import asyncio # 비동기 라이브러리 임포트 def 대신 async def로 함수 선언 # 이렇게 선언된 함수를 (네이티브) 코루틴이..
-
파이썬 효율적인 리스트 사용법Python/이것저것 파이썬 2022. 7. 24. 05:57
리스트 컴프리헨션이 가장 빠르다. import time def time_log(original_fn): def wrapper_fn(*args, **kwargs): start_time = time.time() result = original_fn(*args, **kwargs) end_time = time.time() print(f"Working Time [{original_fn.__name__}]: {end_time - start_time}") return result return wrapper_fn @time_log def list_append(): a = list(range(100000)) a2 = list() for i in a: a2.append(i * 2) print(a2[99999]) @time..
-
MixinPython/이것저것 파이썬 2022. 7. 20. 14:25
믹스인. 다중 상속. 코드 재사용의 목적. 일반적인 행동을 캡슐화 함. 믹스인 자체로는 유용하지 않음. 의존을 함. class BaseTokenizer: def __init__(self, token: str): self.token: str = token def __iter__(self): yield from self.token.split('-') test = BaseTokenizer('zxcv-zcv-zcvzxsfdsdf-sfdf') for each in test: print(each) print(list(test)) 일종의 데코레이터 같은 역할을 함. class BaseTokenizer: def __init__(self, token: str): self.token: str = token def __it..
-
시퀸스 생성: __getitem__Python/이것저것 파이썬 2022. 7. 17. 06:56
__getitem__ 매직 메서드를 이용하면, 자체 시퀸스를 생성할 수 있다. class Items: def __init__(self, *values): self._values = list(values) def __len__(self): return len(self._values) def __getitem__(self, item): """자체 시퀸스 생성""" return self._values.__getitem__(item) items = Items(1, 2, 3, 4, 5) print(len(items)) print(items[1:3])
-
파이썬 slicePython/이것저것 파이썬 2022. 7. 17. 06:44
slice 내장 객체가 있다. numbers = (1, 2, 3, 4, 5) print(numbers[2::2]) # (3, 5) interval = slice(2, None, 2) print(numbers[interval]) # (3, 5) interval = slice(3) print(numbers[interval]) # (1, 2, 3) interval = slice(2, 4) print(numbers[interval]) # (3, 4) interval = slice(2, None) print(numbers[interval]) # (3, 4, 5)
-
[Python, Sqlite] 딕셔너리(사전형)로 row 바로 받기Python/이것저것 파이썬 2021. 12. 23. 13:32
[Python, Sqlite] 딕셔너리(dict, dictionary)로 row 바로 받기 https://docs.python.org/3/library/sqlite3.html#row-objects import sqlite3 con = sqlite3.connect(':memory:') cur = con.cursor() cur.execute( ''' create table stocks (date text, trans text, symbol text, qty real, price real) ''' ) cur.execute( '''insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)''' ) con.commit() cur.close() con.row_..