Pythonにおける代表的な機能とよく出遭う課題の要点を整理します。
JSONのエンコード・デコード処理
json.dumps():PythonオブジェクトをJSON文字列に変換します。主に辞書型を文字列にシリアライズする用途で用いられます。json.loads():JSON文字列をPythonの辞書型などにデシリアライズします。- online JSON validator: JSON.cn
Python 2 と Python 3における文字列とエンコーディング
- Python 2ではデフォルトがASCII、Python 3ではUTF-8です。
- ソースファイル内でのエンコーディング宣言:
# -*- coding: utf-8 -*- - 文字列表現とエンコーディングの抽象化:
- Python 2の
strはバイト列(エンコード済みデータ)を表し、unicodeは抽象的な文字列表現(内部形式)を示します。 .encode()はunicodeからバイト列への変換、.decode()は逆方向の変換です。- UTF-8やShift_JISなどの具体的な符号化方式と抽象層(Unicode)を経由することで、柔軟なエンコーディング変換が可能になります。
- Python 2の
クイックソートアルゴリズム
分割統治法に基づく高速なソート手法です。
- 最良・平均時間計算量:O(n log n)
- 最悪時間計算量:O(n²)
- 安定性:不稳定( sama 値の相対順序が保たれない)
def quick_sort(sequence, low_index, high_index):
if low_index >= high_index:
return
pivot = sequence[low_index]
left, right = low_index, high_index
while left < right:
while left < right and sequence[right] >= pivot:
right -= 1
sequence[left] = sequence[right]
while left < right and sequence[left] < pivot:
left += 1
sequence[right] = sequence[left]
sequence[left] = pivot
quick_sort(sequence, low_index, left - 1)
quick_sort(sequence, left + 1, high_index)
# 使用例
data = [54, 26, 93, 77, 77, 31, 44, 55, 20]
print("before:", data)
quick_sort(data, 0, len(data) - 1)
print("after: ", data)
super()の利用と多重継承対応
継承階層におけるメソッド解決順序(MRO)を正しく扱い、多重継承下での初期化やメソッド呼び出しを行う場合にsuper()が活用されます。
class BaseService:
def __init__(self):
self.origin = 'Base instance'
print('Initialize base')
def display(self, label):
print(f'{label} from base')
class ExtendedService(BaseService):
def __init__(self):
super().__init__()
print('Initialize extended')
def display(self, label):
super().display(label)
print('Extended behavior added')
print(self.origin)
パッケージ化に必要な__init__.py
ディレクトリに__init__.pyを配置することで、そのディレクトリをPythonのパッケージとして認識させることが可能です。
デコレータとその応用
関数やメソッドの振る舞いを機能追加するための構文です。
def logging_decorator(target_func):
def wrapper(*args, **kwargs):
print("[LOG] Starting:", target_func.__name__)
result = target_func(*args, **kwargs)
print("[LOG] Finished:", target_func.__name__)
return result
return wrapper
@logging_decorator
def example_function(value: int) -> str:
print(f"Processing {value}")
return "complete"
# 実行
example_function(100)
def html_header(func):
def inner(*args, **kwargs):
return f"<h1>{func(*args, **kwargs)}</h1>"
return inner
def html_td(func):
def inner(*args, **kwargs):
return f"<td>{func(*args, **kwargs)}</td>"
return inner
@html_header
@html_td
def output():
return "sample"
print(output()) # <h1><td>sample</td></h1>
__new__によるシングルトン実装
オブジェクト生成時のメモリ確保を制御することで、インスタンスが1つだけ存在することを保証します。
class Singleton:
__instance = None
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = super().__new__(cls)
return cls.__instance
# 実行例
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2) # True
イテラブルとイテレータの違い
イテレーション操作を理解する上で重要な2つの概念です。
- イテラブル:
__iter__()メソッドを持つオブジェクト。for文の対象にできます。 - イテレータ:
__iter__()と__next__()の両方を持つオブジェクト。順次要素を返却します。
from collections.abc import Iterable
print(isinstance([], Iterable)) # True
print(isinstance(123, Iterable)) # False
class CustomIterable:
def __init__(self):
self._data = []
def append(self, item):
self._data.append(item)
def __iter__(self):
return CustomIterator(self._data)
class CustomIterator:
def __init__(self, data):
self._data = data
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index < len(self._data):
item = self._data[self._index]
self._index += 1
return item
raise StopIteration()
# 実行確認
items = CustomIterable()
items.append(10)
items.append(20)
items.append(30)
for num in items:
print(num)
スレッドとプロセスの特徴
- スレッド:同一プロセス内のスレッド間では、メモリ空間(特にグローバル変数)を共有できます。
- プロセス:それぞれ独立したメモリ空間を持つため、グローバル変数の共有は別途通信機構が必要です。
import threading
import time
class Worker(threading.Thread):
def run(self):
for _ in range(3):
time.sleep(1)
print("Working...")
self.task_login()
self.task_register()
def task_login(self):
print("Login complete")
def task_register(self):
print("Registration complete")
if __name__ == "__main__":
worker = Worker()
worker.start()