[Python] 기초

이정연·2022년 12월 3일
0

👋🏻 Intro

본 포스팅은 나의 파이썬 기초를 탄탄히 다지기 위하여 작성한다. 따라서 여느 파이썬 기본 교재의 목차와 비교해보았을 때 뒤죽박죽일 수 있음을 감안해주길 바란다.

List vs Tuple

가변성

  • 리스트는 가변 객체이고 튜플은 불변 객체이다.
test_list = [1,2,3,4,5]
test_tuple = (1,2,3,4,5)
test_tuple[0] = 6
print(test_tuple)

Error!

메모리

  • 메모리 사용량 [리스트 > 튜플]
  • 왜? 리스트는 가변성이 있기에 append에 대비하여 여분의 메모리를 확보하고 있어야 함.
  • 반면 튜플은 불변이기에 딱~~ 그 크기만큼만 최소한의 메모리만 확보하고 있으면 됨

디버깅

  • 대규모 프로젝트에서 튜플이 디버깅 하기가 더욱 쉽다.
  • 왜냐하면 불변이기에 오류 추적이 더욱 쉽기 때문이다.

파이썬 메모리 관리

파이썬은 메모리를 관리하기위해 숨겨진 힙 스페이스(heap space)를 사용한다. 모든 객체와 자료 구조들이 이 곳에 저장된다. 인터프리터가 스페이스를 관리하기 때문에 심지어 프로그래머 조차도 이 공간에 대해 접근하지 못한다. 더 나아가, 파이썬은 사용되지 않은 메모리를 재활용하고 메모리를 지워 힙 스페이스에서 사용 가능하게 하는 빌트인 가비지 컬렉터(garbage collector)를 소유하고 있다.

Compile? Interpreter?

  • 흔히들 파이썬이 인터프리터 언어라고 알고 있다.
  • 엄밀히 말하면 반은 컴파일이고 반은 인터프리터이다.
  • [.py]로 작성된 파일은 바이트 코드로 먼저 컴파일 되고 이 바이트코드가 인터프리터에 의하여 실행되는 구조이다.

데코레이터

사용 목적

# Why we need decorator?
def func1():
    print("func1")
def func2():
    print("func2")
def func3():
    print("func3")
def funcN():
    print("funcN")
print(func1())
print(func2())
print(func3())
print(funcN())

func1
func2
func3
funcN

간단한 함수다. 우리는 각각의 함수에 새로운 기능 추가를 원한다.
예를 들어, func1에 현재 시각을 출력 기능을 5번 추가하자.

import datetime
# Why we need decorator?
def func1():
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print("func1")
def func2():
    print("func2")
def func3():
    print("func3")
def funcN():
    print("funcN")

그러나 갑자기 다른 모든 함수들에 대해서도 동일한 기능을 추가하고 싶어졌다. 그러면 어떻게 해야할까? 직관적으로 아래처럼 할 것이다.

import datetime
# Why we need decorator?
def func1():
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print("func1")
def func2():
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print("func2")
def func3():
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print("func3")
def funcN():
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print(datetime.datetime.now())
    print("funcN")

만약 [N=100]이라고 한다면 우리는 100번의 노가다 작업을 해야할 것이다. 너무 끔찍하다 ...! 😱

이와 같은 불상사를 방지하기 위하여 등장한 것이 바로 [데코레이터] 기능이다!

데코레이터 기능을 사용한다면 아래와 같이 간편하게 코딩을 할 수 있다.

import datetime
# Why we need decorator?
def datetime_deco(func):
    def decorated():
        print(datetime.datetime.now())
        print(datetime.datetime.now())
        print(datetime.datetime.now())
        print(datetime.datetime.now())
        print(datetime.datetime.now())
        func()
    return decorated
@datetime_deco        
def func1():
    print("func1")
@datetime_deco
def func2():
    print("func2")
@datetime_deco
def func3():
    print("func3")
@datetime_deco
def funcN():
    print("funcN")

func1()
func2()
func3()
funcN()

2022-11-30 21:45:42.942180
2022-11-30 21:45:42.942204
2022-11-30 21:45:42.942209
2022-11-30 21:45:42.942212
2022-11-30 21:45:42.942214
func1
2022-11-30 21:45:42.942220
2022-11-30 21:45:42.942222
2022-11-30 21:45:42.942225
2022-11-30 21:45:42.942228
2022-11-30 21:45:42.942230
func2
2022-11-30 21:45:42.942235
2022-11-30 21:45:42.942237
2022-11-30 21:45:42.942240
2022-11-30 21:45:42.942242
2022-11-30 21:45:42.942245
func3
2022-11-30 21:45:42.942250
2022-11-30 21:45:42.942252
2022-11-30 21:45:42.942255
2022-11-30 21:45:42.942257
2022-11-30 21:45:42.942260
funcN

profile
0x68656C6C6F21

0개의 댓글