
【Python 100日チャレンジ】 Day 34 - クラス変数とメソッド
今までは、
「1つのオブジェクト=1人分のデータ」
という世界で Python を学んできました。
でも今日は一段レベルアップ。
👉 クラス「全体」でデータと処理を管理する方法 を学びます。
それが クラス変数 & クラスメソッド です!🔥
⭐⭐⭐ (30分で完読)
🎯 今日の学習目標
クラス変数とインスタンス変数の違いを理解する
@classmethodデコレータの使い方を学ぶ
@staticmethodデコレータの使い方を学ぶ
3種類のメソッドタイプの違いを知る
⭐⭐⭐ (35-45分で完読)
📚 事前知識
🎯 学習目標1: クラス変数とインスタンス変数の違いを理解する
インスタンス変数の復習
各オブジェクトが独立して持つ変数です。
class Dog:
def __init__(self, name, age):
self.name = name # インスタンス変数
self.age = age # インスタンス変数
dog1 = Dog("ポチ", 3)
dog2 = Dog("タロウ", 5)
print(dog1.name, dog1.age) # ポチ 3
print(dog2.name, dog2.age) # タロウ 5クラス変数
すべてのインスタンスが共有する変数です。
class Dog:
species = "Canis familiaris" # クラス変数(すべての犬は同じ種)
def __init__(self, name, age):
self.name = name
self.age = age
dog1 = Dog("ポチ", 3)
dog2 = Dog("タロウ", 5)
# すべてのインスタンスが同じ値を共有
print(dog1.species) # Canis familiaris
print(dog2.species) # Canis familiaris
print(Dog.species) # Canis familiaris (クラスで直接アクセス)
# クラス変数変更 - すべてのインスタンスに影響!
Dog.species = "イヌ科"
print(dog1.species) # イヌ科
print(dog2.species) # イヌ科重要な違い
class Counter:
count = 0 # クラス変数
def __init__(self, name):
self.name = name # インスタンス変数
Counter.count += 1 # クラス変数を増加
c1 = Counter("1番目")
c2 = Counter("2番目")
c3 = Counter("3番目")
print(f"合計{Counter.count}個作成") # 合計3個作成
print(c1.name, c2.name, c3.name) # 1番目 2番目 3番目クラス変数の注意点
間違い1: インスタンスでクラス変数を変更
class Example:
shared = "共有値"
def __init__(self, name):
self.name = name
obj1 = Example("1番目")
obj2 = Example("2番目")
# ❌ 間違った方法 - インスタンス変数を作ってしまう!
obj1.shared = "変更された値"
print(obj1.shared) # 変更された値 (obj1のインスタンス変数)
print(obj2.shared) # 共有値 (クラス変数)
print(Example.shared) # 共有値 (クラス変数)
# ✅ 正しい方法 - クラスで変更
Example.shared = "本当に変更された値"
print(obj1.shared) # 変更された値 (インスタンス変数が優先)
print(obj2.shared) # 本当に変更された値 (クラス変数)間違い2: ミュータブルオブジェクトをクラス変数として使用
class BadExample:
items = [] # ❌ 危険! すべてのインスタンスが同じリストを共有
def __init__(self, name):
self.name = name
def add_item(self, item):
self.items.append(item) # クラス変数に追加される!
obj1 = BadExample("1番目")
obj2 = BadExample("2番目")
obj1.add_item("A")
obj2.add_item("B")
print(obj1.items) # ['A', 'B'] (意図していない!)
print(obj2.items) # ['A', 'B'] (意図していない!)解決策:
class GoodExample:
def __init__(self, name):
self.name = name
self.items = [] # ✅ インスタンス変数で!
def add_item(self, item):
self.items.append(item)
obj1 = GoodExample("1番目")
obj2 = GoodExample("2番目")
obj1.add_item("A")
obj2.add_item("B")
print(obj1.items) # ['A']
print(obj2.items) # ['B']🎯 学習目標2: @classmethodデコレータの使い方を学ぶ
クラスメソッドはクラス自体を扱うメソッドです。
基本文法
class MyClass:
class_variable = 0
@classmethod
def class_method(cls):
"""クラスメソッド: 最初のパラメータはcls(クラス自身)"""
return cls.class_variable
# クラスで呼び出し
result = MyClass.class_method()
# インスタンスでも呼び出し可能(でもクラスで呼び出し推奨)
obj = MyClass()
result = obj.class_method()💡 「cls」 vs 「self」:
self:インスタンス自身
cls:クラス自身
実践例題1: オブジェクトカウンター
class Employee:
"""従業員情報を管理するクラス"""
employee_count = 0 # クラス変数
def __init__(self, name, department):
"""コンストラクタ"""
self.name = name
self.department = department
Employee.employee_count += 1
@classmethod
def get_employee_count(cls):
"""クラスメソッド: 総従業員数を返す"""
return cls.employee_count
@classmethod
def reset_count(cls):
"""クラスメソッド: カウンターを初期化"""
cls.employee_count = 0
print("✅ 従業員数が初期化されました。")
def introduce(self):
"""インスタンスメソッド"""
return f"{self.name} ({self.department})"
# 使用
emp1 = Employee("田中太郎", "開発部")
emp2 = Employee("佐藤花子", "デザイン部")
emp3 = Employee("鈴木一郎", "企画部")
# クラスメソッド呼び出し
print(f"総従業員数: {Employee.get_employee_count()}人") # 3人
# インスタンスメソッド呼び出し
print(emp1.introduce()) # 田中太郎 (開発部)
# カウンター初期化
Employee.reset_count()
print(f"総従業員数: {Employee.get_employee_count()}人") # 0人実行結果:
総従業員数: 3人
田中太郎 (開発部)
✅ 従業員数が初期化されました。
総従業員数: 0人実践例題2: ファクトリメソッド
クラスメソッドを使えば様々な方法でオブジェクトを作成できます。
from datetime import datetime
class Person:
"""人物情報を管理するクラス"""
def __init__(self, name, birth_year):
"""通常のコンストラクタ"""
self.name = name
self.birth_year = birth_year
@classmethod
def from_birth_date(cls, name, birth_date):
"""ファクトリメソッド: 生年月日で作成"""
# birth_date形式: "YYYY-MM-DD"
year = int(birth_date.split('-')[0])
return cls(name, year)
@classmethod
def from_age(cls, name, age):
"""ファクトリメソッド: 年齢で作成"""
current_year = datetime.now().year
birth_year = current_year - age
return cls(name, birth_year)
def get_age(self):
"""年齢計算"""
current_year = datetime.now().year
return current_year - self.birth_year
def introduce(self):
"""自己紹介"""
return f"{self.name} ({self.get_age()}歳、{self.birth_year}年生まれ)"
# 様々な方法でオブジェクト作成
person1 = Person("田中太郎", 1990)
person2 = Person.from_birth_date("佐藤花子", "1995-03-15")
person3 = Person.from_age("鈴木一郎", 25)
print(person1.introduce())
print(person2.introduce())
print(person3.introduce())実行結果:
田中太郎 (35歳、1990年生まれ)
佐藤花子 (30歳、1995年生まれ)
鈴木一郎 (25歳、2000年生まれ)実践例題3: 設定管理クラス
class Config:
"""アプリケーション設定を管理するクラス"""
_settings = {
"debug": False,
"language": "ja",
"timeout": 30
}
@classmethod
def get(cls, key, default=None):
"""設定値を取得"""
return cls._settings.get(key, default)
@classmethod
def set(cls, key, value):
"""設定値を保存"""
cls._settings[key] = value
print(f"✅ {key} = {value}")
@classmethod
def update(cls, **kwargs):
"""複数の設定を一度に更新"""
for key, value in kwargs.items():
cls._settings[key] = value
print(f"✅ {len(kwargs)}個の設定が更新されました。")
@classmethod
def print_all(cls):
"""すべての設定を出力"""
print("\n" + "="*40)
print("現在の設定")
print("="*40)
for key, value in cls._settings.items():
print(f"{key}: {value}")
print("="*40 + "\n")
# 使用 - インスタンス作成なしで使用!
Config.print_all()
Config.set("debug", True)
Config.set("timeout", 60)
Config.update(language="en", max_connections=100)
Config.print_all()
print(f"Debugモード: {Config.get('debug')}")
print(f"言語: {Config.get('language')}")実行結果:
========================================
現在の設定
========================================
debug: False
language: ja
timeout: 30
========================================
✅ debug = True
✅ timeout = 60
✅ 2個の設定が更新されました。
========================================
現在の設定
========================================
debug: True
language: en
timeout: 60
max_connections: 100
========================================
Debugモード: True
言語: en🎯 学習目標3: @staticmethodデコレータの使い方を学ぶ
静的メソッドはクラスやインスタンスと無関係な独立した関数です。
@staticmethod vs @classmethod vs インスタンスメソッド
class MyClass:
class_variable = "クラス変数"
def __init__(self, value):
self.instance_variable = value
# インスタンスメソッド
def instance_method(self):
"""selfを通じてインスタンスにアクセス"""
return f"インスタンス: {self.instance_variable}"
# クラスメソッド
@classmethod
def class_method(cls):
"""clsを通じてクラスにアクセス"""
return f"クラス: {cls.class_variable}"
# 静的メソッド
@staticmethod
def static_method(x, y):
"""selfもclsもない - 独立した関数"""
return x + y
# 使用
obj = MyClass("値")
print(obj.instance_method()) # インスタンス: 値
print(MyClass.class_method()) # クラス: クラス変数
print(MyClass.static_method(5, 3)) # 8いつ静的メソッドを使うか?
ユーティリティ関数をクラスにまとめる時に使います。
class MathUtils:
"""数学ユーティリティクラス"""
@staticmethod
def is_even(n):
"""偶数判定"""
return n % 2 == 0
@staticmethod
def is_prime(n):
"""素数判定"""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
@staticmethod
def factorial(n):
"""階乗計算"""
if n <= 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result
# インスタンス作成なしで使用
print(MathUtils.is_even(10)) # True
print(MathUtils.is_prime(17)) # True
print(MathUtils.factorial(5)) # 120実践例題: 日付ユーティリティ
from datetime import datetime, timedelta
class DateUtils:
"""日付関連ユーティリティクラス"""
@staticmethod
def is_weekend(date):
"""週末かどうか確認"""
# weekday(): 月(0) ~ 日(6)
return date.weekday() >= 5
@staticmethod
def add_business_days(date, days):
"""営業日基準で日付を追加"""
current = date
added = 0
while added < days:
current += timedelta(days=1)
if not DateUtils.is_weekend(current):
added += 1
return current
@staticmethod
def format_date(date, format_type="default"):
"""日付フォーマット"""
formats = {
"default": "%Y-%m-%d",
"japanese": "%Y年%m月%d日",
"american": "%m/%d/%Y",
"full": "%Y年%m月%d日 (%A)"
}
return date.strftime(formats.get(format_type, formats["default"]))
@staticmethod
def days_between(date1, date2):
"""2つの日付間の日数"""
delta = date2 - date1
return abs(delta.days)
# 使用
today = datetime(2025, 4, 3) # 木曜日
print(f"今日は週末? {DateUtils.is_weekend(today)}")
next_business_day = DateUtils.add_business_days(today, 5)
print(f"5営業日後: {DateUtils.format_date(next_business_day, 'japanese')}")
date1 = datetime(2025, 1, 1)
date2 = datetime(2025, 12, 31)
print(f"2025年は{DateUtils.days_between(date1, date2)}日")実行結果:
今日は週末? False
5営業日後: 2025年04月10日
2025年は364日🎯 学習目標4: 3種類のメソッドタイプの違いを知る
実践例題: 完全なクラス設計
書籍管理システム
class Book:
"""書籍を管理するクラス"""
# クラス変数
total_books = 0
categories = ["小説", "科学", "歴史", "技術", "自己啓発"]
def __init__(self, title, author, isbn, category, price):
"""コンストラクタ"""
self.title = title
self.author = author
self.isbn = isbn
self.category = category
self.price = price
Book.total_books += 1
# インスタンスメソッド
def get_info(self):
"""書籍情報を返す"""
return f"{self.title} ({self.author})"
def apply_discount(self, rate):
"""割引適用"""
discount = self.price * (rate / 100)
return self.price - discount
# クラスメソッド
@classmethod
def get_total_books(cls):
"""総書籍数を返す"""
return cls.total_books
@classmethod
def from_string(cls, book_string):
"""ファクトリメソッド: 文字列で作成"""
# 形式: "タイトル|著者|ISBN|カテゴリ|価格"
parts = book_string.split('|')
return cls(
title=parts[0],
author=parts[1],
isbn=parts[2],
category=parts[3],
price=int(parts[4])
)
@classmethod
def add_category(cls, category):
"""カテゴリ追加"""
if category not in cls.categories:
cls.categories.append(category)
print(f"✅ '{category}'カテゴリが追加されました。")
else:
print(f"❌ '{category}'カテゴリはすでに存在します。")
# 静的メソッド
@staticmethod
def validate_isbn(isbn):
"""ISBN有効性検査"""
# 簡単な検査: 13桁の数字
return isbn.isdigit() and len(isbn) == 13
@staticmethod
def calculate_bulk_discount(price, quantity):
"""大量購入割引計算"""
if quantity >= 10:
return price * 0.8 # 20%割引
elif quantity >= 5:
return price * 0.9 # 10%割引
else:
return price
def __str__(self):
"""文字列表現"""
return f"[{self.category}] {self.title} - {self.author} ({self.price:,}円)"
# 使用例
print("="*50)
print("書籍管理システム")
print("="*50 + "\n")
# 通常のコンストラクタ
book1 = Book("Python入門", "田中太郎", "9781234567890", "技術", 3500)
print(book1)
# ファクトリメソッド
book2 = Book.from_string("クリーンコード|ロバート・マーティン|9789876543210|技術|3300")
print(book2)
book3 = Book("ハリー・ポッター", "J.K.ローリング", "9781111111111", "小説", 2500)
print(book3)
print(f"\n合計{Book.get_total_books()}冊登録\n")
# 静的メソッド使用
isbn = "9781234567890"
if Book.validate_isbn(isbn):
print(f"✅ {isbn}は有効なISBNです。")
# 大量購入割引
print(f"\n5冊購入時: {Book.calculate_bulk_discount(3500, 5):,}円")
print(f"10冊購入時: {Book.calculate_bulk_discount(3500, 10):,}円")
# カテゴリ管理
print(f"\n現在のカテゴリ: {Book.categories}")
Book.add_category("漫画")
print(f"更新されたカテゴリ: {Book.categories}")実行結果:
==================================================
書籍管理システム
==================================================
[技術] Python入門 - 田中太郎 (3,500円)
[技術] クリーンコード - ロバート・マーティン (3,300円)
[小説] ハリー・ポッター - J.K.ローリング (2,500円)
合計3冊登録
✅ 9781234567890は有効なISBNです。
5冊購入時: 3,150円
10冊購入時: 2,800円
現在のカテゴリ: ['小説', '科学', '歴史', '技術', '自己啓発']
✅ '漫画'カテゴリが追加されました。
更新されたカテゴリ: ['小説', '科学', '歴史', '技術', '自己啓発', '漫画']💡 実践のコツと注意点
Tip 1: クラス変数はクラスで直接変更する
インスタンスを通じてクラス変数を変更すると新しいインスタンス変数が作成されるので、必ずクラス名で直接変更しましょう。
# ❌ 間違った方法
obj.class_var = "変更" # インスタンス変数作成
# ✅ 正しい方法
ClassName.class_var = "変更" # クラス変数変更Tip 2: ミュータブルオブジェクトをクラス変数にしない
リストや辞書のようなミュータブルオブジェクトをクラス変数にするとすべてのインスタンスが同じオブジェクトを共有するので注意しましょう。
# ❌ 危険なパターン
class BadExample:
items = [] # すべてのインスタンスが共有
# ✅ 安全なパターン
class GoodExample:
def __init__(self):
self.items = [] # 各インスタンスが独立Tip 3: ファクトリメソッドで柔軟なオブジェクト作成
クラスメソッドを活用すれば様々な方法でオブジェクトを作成でき、コードがより柔軟になります。
@classmethod
def from_string(cls, data_string):
"""文字列からオブジェクト作成"""
parts = data_string.split('|')
return cls(parts[0], parts[1])Tip 4: 静的メソッドは名前空間の役割
関連するユーティリティ関数をクラスにまとめるとコード構造が明確になり管理が楽になります。
class Utils:
@staticmethod
def validate_email(email):
return '@' in email
@staticmethod
def format_phone(phone):
return phone.replace('-', '')🧪 練習問題
問題1: 学生管理システム
以下の要件を満たす「Student」クラスを作成してください:
要件:
クラス変数で総学生数、学校名を管理
インスタンスメソッド:成績追加、平均計算
クラスメソッド:総学生数を返す、学校名変更
静的メソッド:成績計算(A/B/C/D/F)
# 使用例
Student.set_school("Python高校")
s1 = Student("田中太郎", "2024001")
s1.add_score("数学", 95)
s1.add_score("英語", 88)
s2 = Student("佐藤花子", "2024002")
s2.add_score("数学", 78)
print(f"総学生数: {Student.get_student_count()}人")
print(f"成績: {Student.calculate_grade(92)}")💡 ヒント (まず自分で考えてみてください!)
クラス変数は`cls`でアクセスし、インスタンス変数は「self」でアクセスします。「@classmethod」は最初のパラメータが「cls」、「@staticmethod」はパラメータなしです。
✅ 正解 (下にスクロールして確認)
↓
↓
↓
↓
↓
class Student:
"""学生情報を管理するクラス"""
school_name = ""
student_count = 0
def __init__(self, name, student_id):
"""コンストラクタ"""
self.name = name
self.student_id = student_id
self.scores = {}
Student.student_count += 1
# インスタンスメソッド
def add_score(self, subject, score):
"""成績追加"""
self.scores[subject] = score
print(f"✅ {self.name} - {subject}: {score}点")
def get_average(self):
"""平均計算"""
if not self.scores:
return 0
return sum(self.scores.values()) / len(self.scores)
def print_report(self):
"""成績表出力"""
print(f"\n{'='*40}")
print(f"学校: {Student.school_name}")
print(f"学生: {self.name} ({self.student_id})")
print(f"{'-'*40}")
for subject, score in self.scores.items():
grade = Student.calculate_grade(score)
print(f"{subject}: {score}点 ({grade})")
print(f"{'-'*40}")
avg = self.get_average()
print(f"平均: {avg:.2f}点 ({Student.calculate_grade(avg)})")
print(f"{'='*40}\n")
# クラスメソッド
@classmethod
def get_student_count(cls):
"""総学生数を返す"""
return cls.student_count
@classmethod
def set_school(cls, name):
"""学校名設定"""
cls.school_name = name
print(f"🏫 学校名: {name}")
# 静的メソッド
@staticmethod
def calculate_grade(score):
"""成績計算"""
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
# テスト
Student.set_school("Python高校")
s1 = Student("田中太郎", "2024001")
s1.add_score("数学", 95)
s1.add_score("英語", 88)
s1.add_score("科学", 92)
s2 = Student("佐藤花子", "2024002")
s2.add_score("数学", 78)
s2.add_score("英語", 85)
print(f"\n総学生数: {Student.get_student_count()}人\n")
s1.print_report()
s2.print_report()
print(f"成績例: {Student.calculate_grade(92)}")問題2: 時間変換ユーティリティ
時間変換機能を提供する「TimeConverter」クラスを作成してください:
要件:
静的メソッドのみ使用(インスタンス作成不要)
秒 → 時:分:秒 変換
時:分:秒 → 秒 変換
時間フォーマット
# 使用例
print(TimeConverter.seconds_to_hms(3665)) # "1:01:05"
print(TimeConverter.hms_to_seconds("1:01:05")) # 3665
print(TimeConverter.format_time(3665)) # "1時間1分5秒"✅ 正解 (下にスクロールして確認)
↓
↓
↓
↓
↓
class TimeConverter:
"""時間変換ユーティリティクラス"""
@staticmethod
def seconds_to_hms(seconds):
"""秒を時:分:秒形式に変換"""
hours = seconds // 3600
minutes = (seconds % 3600) // 60
secs = seconds % 60
return f"{hours}:{minutes:02d}:{secs:02d}"
@staticmethod
def hms_to_seconds(hms_string):
"""時:分:秒形式を秒に変換"""
parts = hms_string.split(':')
hours = int(parts[0])
minutes = int(parts[1])
secs = int(parts[2])
return hours * 3600 + minutes * 60 + secs
@staticmethod
def format_time(seconds):
"""秒を読みやすい形式に変換"""
hours = seconds // 3600
minutes = (seconds % 3600) // 60
secs = seconds % 60
parts = []
if hours > 0:
parts.append(f"{hours}時間")
if minutes > 0:
parts.append(f"{minutes}分")
if secs > 0 or not parts:
parts.append(f"{secs}秒")
return ''.join(parts)
@staticmethod
def add_times(time1, time2):
"""2つの時間を足す(時:分:秒形式)"""
seconds1 = TimeConverter.hms_to_seconds(time1)
seconds2 = TimeConverter.hms_to_seconds(time2)
total = seconds1 + seconds2
return TimeConverter.seconds_to_hms(total)
# テスト
print(TimeConverter.seconds_to_hms(3665))
print(TimeConverter.hms_to_seconds("1:01:05"))
print(TimeConverter.format_time(3665))
print(TimeConverter.format_time(65))
print(TimeConverter.add_times("1:30:45", "2:45:30"))実行結果:
1:01:05
3665
1時間1分5秒
1分5秒
4:16:15📝 今日学んだ内容のまとめ
📌 3種類のメソッドタイプ
インスタンスメソッド
最初のパラメータ:self
アクセス可能:インスタンス変数
使用目的:個別オブジェクトの動作
クラスメソッド (@classmethod)
最初のパラメータ:cls
アクセス可能:クラス変数
使用目的:クラスレベルの作業、ファクトリメソッド
静的メソッド (@staticmethod)
最初のパラメータ:なし
アクセス可能:両方不可
使用目的:独立したユーティリティ関数
📌 いつ何を使うか?
class Example:
class_var = 0
def __init__(self, value):
self.instance_var = value
# ✅ インスタンスメソッド: インスタンスデータが必要
def instance_method(self):
return self.instance_var
# ✅ クラスメソッド: クラスデータが必要またはファクトリ
@classmethod
def class_method(cls):
return cls.class_var
# ✅ 静的メソッド: 両方必要ない独立関数
@staticmethod
def static_method(x, y):
return x + y🔗 関連資料
📚 前回の学習
前回は、インスタンス変数とメソッド、Propertyデコレータを活用した安全な属性管理方法を学びました!
📚 次回の学習
Day 35: 継承の基礎 ⭐⭐⭐
次回は、継承(Inheritance)の概念と必要性、親クラスと子クラスの関係、「super()」関数の使い方、メソッドオーバーライドの基礎を学びます!
📚 シリーズをまとめて読む
Python 100日チャレンジの全記事は、
マガジン「Python 100日チャレンジ」 でまとめて読めます 😊
よろしければ、フォローしていただけると嬉しいです!
🚀 遅いと思った時が一番早い時期です!🚀
Day 34/100 | Phase 4:オブジェクト指向プログラミング | #100DaysOfPython