関数の定義(def)とデフォルト引数の罠
Python
def greet(name, message="こんにちは"):
return f"{name}さん、{message}"
print(greet("佐藤")) # 佐藤さん、こんにちは
⚠️ デフォルト引数の罠 引数の初期値にリストなどの可変オブジェクト(mutable)を指定すると、関数呼び出し間でデータが保持されてバグの原因になります。必ず
Noneを使いましょう。
Python
# 危険な例: def add_item(item, items=[]):
# 安全な例
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
可変長引数(*args, kwargs)
Python
def flex_func(*args, **kwargs):
# args: 位置引数がタプルで入る
# kwargs: キーワード引数が辞書で入る
print("位置引数:", args)
print("キーワード引数:", kwargs)
flex_func(1, 2, 3, name="Alice", age=25)
無名関数(lambda 式)と高階関数
Python
numbers = [1, 2, 3, 4, 5]
# map(): 各要素に処理を適用
doubled = list(map(lambda x: x * 2, numbers)) # [2, 4, 6, 8, 10]
# filter(): 抽出条件に合う要素のみ残す
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
変数スコープ(local / global / nonlocal)
Python
count = 0
def increment():
global count # グローバル変数を変更する宣言
count += 1
def outer():
x = 10
def inner():
nonlocal x # 親関数のローカル変数を変更する宣言
x += 5
inner()
print(x) # 15
モジュールとパッケージの記述法
Python
# 標準ライブラリや外部モジュールの読み込み
import math
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=7)

コメント