Python

 다양한 특징을 가진 강력하고 유연한 프로그래밍 언어.

특징

인터프리터 언어

파이썬은 인터프리터 언어.
이는 코드가 한 줄씩 실행되며, 컴파일 과정 없이 바로 실행할 수 있다는 의미.

장점:

단점:

예를 들어, 다음과 같은 코드를 바로 실행하고 결과를 확인할 수 있다:

1
2
3
4
>>> x = 5
>>> y = 3
>>> print(x + y)
8

동적 타이핑

파이썬은 변수의 타입을 미리 선언할 필요가 없다.
변수는 할당되는 값에 따라 자동으로 타입이 결정된다:

장점:

단점:

1
2
3
4
# 같은 변수에 다른 타입의 값을 자유롭게 할당할 수 있습니다
x = 42          # 정수
x = "Hello"     # 문자열
x = [1, 2, 3]   # 리스트

객체 지향 프로그래밍 지원

파이썬은 클래스와 객체를 사용한 객체 지향 프로그래밍을 완벽하게 지원한다:

장점:

단점:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

풍부한 표준 라이브러리와 생태계

장점:

단점:

1
2
3
4
5
6
7
8
9
# 데이터 분석
import pandas as pd
import numpy as np

# 웹 개발
from flask import Flask

# 머신러닝
from sklearn import linear_model
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 가상 환경과 의존성 관리 도구 사용
"""
# requirements.txt 생성
pip freeze > requirements.txt

# 가상 환경 생성
python -m venv myenv

# 의존성 설치
pip install -r requirements.txt
"""

크로스 플랫폼 지원

장점:

단점:

문법적 특징

들여쓰기를 통한 코드 블록 구분

장점:

단점:

1
2
3
4
5
6
7
8
9
def calculate_grade(score):
    if score >= 90:
        return 'A'
    elif score >= 80:
        return 'B'
    elif score >= 70:
        return 'C'
    else:
        return 'F'

리스트 컴프리헨션과 제너레이터 표현식

장점:

단점:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# 적절한 주석과 분리로 가독성 향상
# 복잡한 컴프리헨션은 일반 반복문으로 분리
numbers = [1, 2, 3, 4, 5]

# 간단한 경우 리스트 컴프리헨션 사용
squares = [x**2 for x in numbers]

# 복잡한 경우 일반 반복문 사용
filtered_squares = []
for x in numbers:
    if x % 2 == 0:
        if x**2 > 10:
            filtered_squares.append(x**2)

다중 상속과 믹스인

장점:

단점:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 믹스인 패턴과 명시적 메서드 해결 순서 사용
class LoggerMixin:
    def log(self, message):
        print(f"[LOG] {message}")

class ServiceMixin:
    def service_method(self):
        self.log("Service method called")

class MyService(ServiceMixin, LoggerMixin):
    pass

# MRO(Method Resolution Order) 확인
print(MyService.__mro__)

덕 타이핑

장점:

단점:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# 프로토콜과 추상 기본 클래스 사용
from typing import Protocol
from abc import ABC, abstractmethod

class Drawable(Protocol):
    def draw(self) -> None: 

class Shape(ABC):
    @abstractmethod
    def draw(self) -> None:
        pass

class Circle(Shape):
    def draw(self) -> None:
        print("Drawing circle")

파이썬의 단점과 해결 방안

실행 속도

인터프리터 언어의 특성상 컴파일 언어에 비해 실행 속도가 느리다.

해결 방안
1
2
3
4
5
# Cython 예시
%%cython
def fast_calculation(int x, int y):
    cdef int result = x * y
    return result
1
2
3
4
5
import numpy as np

# 일반 파이썬 리스트 대신 NumPy 배열 사용
array = np.array([1, 2, 3, 4, 5])
result = array * 2  # 빠른 벡터화 연산

GIL(Global Interpreter Lock)로 인한 멀티스레딩 제한

GIL로 인해 멀티코어 CPU를 완전히 활용하기 어렵다.

해결 방안
1
2
3
4
5
6
7
8
from multiprocessing import Pool

def heavy_computation(x):
    return x * x

if __name__ == '__main__':
    with Pool(4) as p:  # 4개의 프로세스 생성
        result = p.map(heavy_computation, range(1000))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import asyncio

async def async_task(name):
    print(f'Task {name} starting')
    await asyncio.sleep(1)
    print(f'Task {name} completed')

async def main():
    tasks = [async_task(f'Task_{i}') for i in range(3)]
    await asyncio.gather(*tasks)

메모리 사용량

동적 타이핑으로 인해 메모리 사용량이 많을 수 있다.

해결 방안
1
2
3
4
5
6
7
8
# 리스트 대신 제네레이터 사용
def number_generator(n):
    for i in range(n):
        yield i ** 2

# 메모리 효율적인 처리
for num in number_generator(1000000):
    process(num)
1
2
3
4
5
6
class MemoryEfficientClass:
    __slots__ = ['name', 'age']  # 인스턴스 속성 제한
    
    def __init__(self, name, age):
        self.name = name
        self.age = age

타입 안정성

동적 타이핑으로 인해 런타임 에러가 발생할 수 있다.

해결 방안
1
2
3
4
5
6
7
8
9
from typing import List, Dict

def calculate_average(numbers: List[float]) -> float:
    return sum(numbers) / len(numbers)

def process_user_data(data: Dict[str, str]) -> None:
    name = data['name']
    email = data['email']
    print(f"Processing user {name} with email {email}")
1
2
# 터미널에서 실행
mypy your_script.py

참고 및 출처


Roadmap

Roadmap - Python