メインコンテンツへスキップ
見出し画像

【Python 100日チャレンジ】Day 39 - 特殊メソッド (__str__、__repr__など)

    クラスを作って、ワクワクしながら print() してみたら...

    <__main__.User object at 0x7f9b8c0a1d90>

    ...は? 🤯
    「いや、名前と年齢が見たかっただけなんだけど...」
    これ、Pythonあるあるですよね。

    せっかく作ったクラスなのに、printしたら意味不明な文字列。
    my_list[0] みたいにブラケットでアクセスしたいのに、できない。

    実はこれ、特殊メソッドを知らないだけなんです。

    len()、str()、[]、+ ── 普段何気なく使ってるこれらの裏側では、 Pythonが「魔法のメソッド」を呼び出しています。

    今日これをマスターすれば、

    print(user)  # → "田中さん (25歳)" ✨

    こんな風に、自分のクラスが "Pythonネイティブ" になります。

    (完読:30分 ⭐⭐⭐⭐)

    🎯 今日の学習目標

    1. 特殊メソッドの概念と活用を理解する

    2. 文字列表現メソッドを実装する

    3. 呼び出し可能オブジェクトとコンテキストマネージャーを作る

    4. イテレータとコンテナプロトコルを実装する

    5. 実践例で総まとめする

    📚 事前知識


    🎯 学習目標 1: 特殊メソッドの概念と活用を理解する

    特殊メソッドの概念

    特殊メソッド(Special Methods)は、Pythonが内部的に呼び出すメソッドです。

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        def __str__(self):
            return f"Point({self.x}, {self.y})"
    
        def __add__(self, other):
            return Point(self.x + other.x, self.y + other.y)
    
    # 特殊メソッドはPythonが自動的に呼び出す
    p1 = Point(1, 2)      # __init__ 呼び出し
    print(p1)             # __str__ 呼び出し
    p2 = Point(3, 4)
    p3 = p1 + p2          # __add__ 呼び出し
    print(p3)             # Point(4, 6)

    なぜ特殊メソッドを使うのか?

    メリット:

    1. Pythonらしいコード: 組み込み型のように動作するクラス

    2. 直感的なインターフェース: `+`、`==`などの演算子が使用可能

    3. プロトコルサポート: イテレータ、コンテキストマネージャーなど標準プロトコル

    4. 性能最適化: Pythonインタプリタが直接呼び出し

    # 特殊メソッドなし
    class NumberWithoutSpecial:
        def __init__(self, value):
            self.value = value
    
        def add(self, other):
            return NumberWithoutSpecial(self.value + other.value)
    
    n1 = NumberWithoutSpecial(10)
    n2 = NumberWithoutSpecial(20)
    n3 = n1.add(n2)  # 不便
    
    # 特殊メソッド使用
    class Number:
        def __init__(self, value):
            self.value = value
    
        def __add__(self, other):
            return Number(self.value + other.value)
    
        def __str__(self):
            return str(self.value)
    
    n1 = Number(10)
    n2 = Number(20)
    n3 = n1 + n2     # Pythonらしい!
    print(n3)        # 30

    🎯 学習目標 2: 文字列表現メソッドを実装する

    __str__ vs __repr__

    二つのメソッドはオブジェクトを文字列で表現しますが、目的が異なります。

    class Book:
        def __init__(self, title, author, year):
            self.title = title
            self.author = author
            self.year = year
    
        def __str__(self):
            """ユーザーフレンドリーな文字列(読みやすい)"""
            return f"'{self.title}' by {self.author}"
    
        def __repr__(self):
            """開発者フレンドリーな文字列(再生成可能)"""
            return f"Book(title='{self.title}', author='{self.author}', year={self.year})"
    
    book = Book("1984", "George Orwell", 1949)
    
    # __str__はprint()で使用
    print(book)           # '1984' by George Orwell
    print(str(book))      # '1984' by George Orwell
    
    # __repr__はインタプリタで使用
    print(repr(book))     # Book(title='1984', author='George Orwell', year=1949)

    ルール:

    • __str__: エンドユーザーが読みやすく

    • __repr__:開発者がデバッグしやすく(可能であれば再生成可能な形式)

    例:ユーザークラス

    from datetime import datetime
    
    class User:
        def __init__(self, username, email, joined_at=None):
            self.username = username
            self.email = email
            self.joined_at = joined_at or datetime.now()
    
        def __str__(self):
            """一般ユーザー向け表現"""
            return f"{self.username} ({self.email})"
    
        def __repr__(self):
            """開発者向け表現(再生成可能)"""
            return (f"User(username='{self.username}', "
                    f"email='{self.email}', "
                    f"joined_at=datetime({self.joined_at.year}, "
                    f"{self.joined_at.month}, {self.joined_at.day}))")
    
    # 使用例
    user = User("alice", "alice@example.com")
    
    print(user)           # alice (alice@example.com)
    print(repr(user))     # User(username='alice', email='alice@example.com', joined_at=datetime(2025, 4, 8))

    __format__ カスタムフォーマット

    f"{obj:spec}"のようにフォーマット指定子を使う時、__format__メソッドが呼び出されます。
    これを実装すると、オブジェクトを様々な形式で表示できます!

    例:時間の長さを表すクラス

    class Duration:
        """時間の長さを表すクラス"""
        def __init__(self, seconds):
            self.seconds = seconds
    
        def __str__(self):
            return f"{self.seconds} seconds"
    
        def __format__(self, format_spec):
            """カスタムフォーマットサポート"""
            if format_spec == 'hms':
                # 時:分:秒 形式
                hours = self.seconds // 3600
                minutes = (self.seconds % 3600) // 60
                secs = self.seconds % 60
                return f"{hours:02d}:{minutes:02d}:{secs:02d}"
            elif format_spec == 'verbose':
                # 詳細形式
                hours = self.seconds // 3600
                minutes = (self.seconds % 3600) // 60
                secs = self.seconds % 60
                return f"{hours}時間 {minutes}分 {secs}秒"
            else:
                # デフォルト形式
                return str(self.seconds)
    
    duration = Duration(3725)  # 1時間 2分 5秒
    
    print(duration)              # 3725 seconds
    print(f"{duration:hms}")     # 01:02:05
    print(f"{duration:verbose}") # 1時間 2分 5秒

    🎯 学習目標 3: 呼び出し可能オブジェクトとコンテキストマネージャーを作る

    __call__ メソッド

    __call__メソッドを定義すると、オブジェクトを関数のように呼び出せます。

    例1:数を掛けるクラス

    class Multiplier:
        """数を掛ける呼び出し可能オブジェクト"""
        def __init__(self, factor):
            self.factor = factor
    
        def __call__(self, x):
            """オブジェクトを関数のように呼び出す"""
            return x * self.factor
    
    # 使用例
    double = Multiplier(2)
    triple = Multiplier(3)
    
    print(double(5))    # 10(関数のように呼び出し!)
    print(triple(5))    # 15
    
    # callable() 関数で確認
    print(callable(double))  # True

    例2:ロガークラス

    from datetime import datetime
    
    class Logger:
        """呼び出し可能なロガーオブジェクト"""
        def __init__(self, prefix="[LOG]"):
            self.prefix = prefix
            self.logs = []
    
        def __call__(self, message):
            """ログメッセージ記録"""
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            log_entry = f"{self.prefix} [{timestamp}] {message}"
            self.logs.append(log_entry)
            print(log_entry)
    
        def get_logs(self):
            return self.logs
    
    # 使用例
    logger = Logger("[INFO]")
    
    logger("アプリケーション起動")          # 関数のように呼び出し!
    logger("データベース接続成功")
    logger("ユーザーログイン: alice")
    
    print("\n全ログ:")
    for log in logger.get_logs():
        print(log)

    例3:キャッシングデコレータ

    class Cached:
        """関数結果をキャッシングする呼び出し可能オブジェクト"""
        def __init__(self, func):
            self.func = func
            self.cache = {}
    
        def __call__(self, *args):
            """キャッシュを確認して関数呼び出し"""
            if args in self.cache:
                print(f"💾 キャッシュ使用: {args}")
                return self.cache[args]
    
            print(f"🔄 計算中: {args}")
            result = self.func(*args)
            self.cache[args] = result
            return result
    
    @Cached
    def fibonacci(n):
        """フィボナッチ数列"""
        if n <= 1:
            return n
        return fibonacci(n - 1) + fibonacci(n - 2)
    
    print(fibonacci(5))
    print(fibonacci(5))  # キャッシュから取得
    print(fibonacci(6))  # 一部はキャッシュ使用

    コンテキストマネージャー(__enter__、__exit__)

    コンテキストマネージャーは「with文」と一緒に使用するオブジェクトです。

    例1:ファイル管理

    class FileManager:
        """ファイル管理コンテキストマネージャー"""
        def __init__(self, filename, mode):
            self.filename = filename
            self.mode = mode
            self.file = None
    
        def __enter__(self):
            """withブロック進入時に呼び出し"""
            print(f"📂 ファイルを開く: {self.filename}")
            self.file = open(self.filename, self.mode)
            return self.file
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            """withブロック終了時に呼び出し"""
            if self.file:
                self.file.close()
                print(f"📁 ファイルを閉じる: {self.filename}")
    
            # 例外処理
            if exc_type is not None:
                print(f"❌ エラー発生: {exc_type.__name__}: {exc_val}")
    
            # False返却時、例外を再発生
            return False
    
    # 使用例
    with FileManager("test.txt", "w") as f:
        f.write("Hello, Context Manager!")
        # ファイルが自動的に閉じられる

    例2:データベース接続管理

    import time
    
    class DatabaseConnection:
        """データベース接続コンテキストマネージャー"""
        def __init__(self, host, database):
            self.host = host
            self.database = database
            self.connection = None
    
        def __enter__(self):
            """接続開始"""
            print(f"🔌 DB接続中: {self.host}/{self.database}")
            time.sleep(0.1)  # 接続シミュレーション
            self.connection = f"Connection<{self.host}/{self.database}>"
            print("✅ 接続成功")
            return self
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            """接続終了"""
            print("🔌 DB接続解除中...")
            time.sleep(0.1)  # 接続解除シミュレーション
            self.connection = None
            print("✅ 接続解除完了")
            return False
    
        def execute(self, query):
            """クエリ実行"""
            if not self.connection:
                raise RuntimeError("接続されていません")
            print(f"📝 クエリ実行: {query}")
            return f"Result of '{query}'"
    
    # 使用例
    with DatabaseConnection("localhost", "mydb") as db:
        result = db.execute("SELECT * FROM users")
        print(f"結果: {result}")
    # 自動的に接続解除

    例3:タイマーコンテキストマネージャー

    import time
    
    class Timer:
        """コード実行時間測定コンテキストマネージャー"""
        def __init__(self, name="コードブロック"):
            self.name = name
            self.start_time = None
            self.elapsed = None
    
        def __enter__(self):
            """タイマー開始"""
            print(f"⏱️  {self.name} 開始...")
            self.start_time = time.time()
            return self
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            """タイマー終了"""
            self.elapsed = time.time() - self.start_time
            print(f"⏱️  {self.name} 完了: {self.elapsed:.4f}秒")
            return False
    
    # 使用例
    with Timer("データ処理"):
        time.sleep(0.5)
        data = [i ** 2 for i in range(1000000)]
    
    with Timer("ファイル作業"):
        with open("test.txt", "w") as f:
            for i in range(10000):
                f.write(f"Line {i}\n")

    🎯 学習目標 4: イテレータとコンテナプロトコルを実装する

    __iter__と__next__

    イテレータプロトコルを実装すると、オブジェクトを`for`ループで使用できます。

    例1:カウントダウンイテレータ

    class Countdown:
        """カウントダウンイテレータ"""
        def __init__(self, start):
            self.current = start
    
        def __iter__(self):
            """イテレータオブジェクト返却(自分自身)"""
            return self
    
        def __next__(self):
            """次の値を返却"""
            if self.current <= 0:
                raise StopIteration
    
            self.current -= 1
            return self.current + 1
    
    # 使用例
    for num in Countdown(5):
        print(num)  # 5, 4, 3, 2, 1

    例2:無限シーケンス生成器

    class FibonacciIterator:
        """フィボナッチ数列無限イテレータ"""
        def __init__(self, max_value=None):
            self.a = 0
            self.b = 1
            self.max_value = max_value
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if self.max_value is not None and self.a > self.max_value:
                raise StopIteration
    
            current = self.a
            self.a, self.b = self.b, self.a + self.b
            return current
    
    # 使用例
    print("100以下のフィボナッチ数列:")
    for num in FibonacciIterator(max_value=100):
        print(num, end=" ")
    print()
    
    # 最初の10個だけ
    from itertools import islice
    print("\n最初の10個:")
    for num in islice(FibonacciIterator(), 10):
        print(num, end=" ")

    コンテナプロトコル

    コンテナのように動作するクラスを作成できます。

    例1:音楽プレイリスト

    class Playlist:
        """音楽プレイリストコンテナ"""
        def __init__(self):
            self.songs = []
    
        def __len__(self):
            """len() 関数サポート"""
            return len(self.songs)
    
        def __getitem__(self, index):
            """インデックスサポート (playlist[0])"""
            return self.songs[index]
    
        def __setitem__(self, index, value):
            """インデックス代入サポート (playlist[0] = song)"""
            self.songs[index] = value
    
        def __delitem__(self, index):
            """delサポート (del playlist[0])"""
            del self.songs[index]
    
        def __contains__(self, song):
            """in演算子サポート (song in playlist)"""
            return song in self.songs
    
        def add(self, song):
            """曲を追加"""
            self.songs.append(song)
    
    # 使用例
    playlist = Playlist()
    playlist.add("Song A")
    playlist.add("Song B")
    playlist.add("Song C")
    
    print(f"プレイリストサイズ: {len(playlist)}")  # 3
    print(f"最初の曲: {playlist[0]}")              # Song A
    print("Song B" in playlist)                    # True
    
    # スライシングサポートのための改善
    playlist[1] = "New Song"
    print(playlist[1])  # New Song

    例2:大文字小文字区別なし辞書

    class CaseInsensitiveDict:
        """大文字小文字区別なし辞書"""
        def __init__(self):
            self._data = {}
    
        def __setitem__(self, key, value):
            """キーを小文字で保存"""
            self._data[key.lower()] = value
    
        def __getitem__(self, key):
            """キーを小文字で検索"""
            return self._data[key.lower()]
    
        def __delitem__(self, key):
            """キーを小文字で削除"""
            del self._data[key.lower()]
    
        def __contains__(self, key):
            """in演算子"""
            return key.lower() in self._data
    
        def __len__(self):
            """辞書サイズ"""
            return len(self._data)
    
        def __repr__(self):
            return f"CaseInsensitiveDict({self._data})"
    
    # 使用例
    config = CaseInsensitiveDict()
    config["API_KEY"] = "secret123"
    
    print(config["api_key"])      # secret123(小文字でアクセス)
    print(config["Api_Key"])      # secret123(大文字小文字混合)
    print("API_KEY" in config)    # True
    print(len(config))            # 1

    🎯 学習目標 5: 実践例で総まとめする

    これまで学んだ特殊メソッドを総合的に活用した実践例です!

    スマートショッピングカート

    from functools import total_ordering
    
    @total_ordering
    class Product:
        """商品クラス"""
        def __init__(self, name, price, stock=100):
            self.name = name
            self.price = price
            self.stock = stock
    
        def __eq__(self, other):
            if not isinstance(other, Product):
                return NotImplemented
            return self.name == other.name
    
        def __lt__(self, other):
            """価格基準比較"""
            if not isinstance(other, Product):
                return NotImplemented
            return self.price < other.price
    
        def __hash__(self):
            """ハッシュ可能(辞書キーとして使用)"""
            return hash(self.name)
    
        def __repr__(self):
            return f"Product('{self.name}', {self.price:,}円, 在庫={self.stock})"
    
    class ShoppingCart:
        """ショッピングカート(全特殊メソッド活用)"""
        def __init__(self):
            self._items = {}  # {Product: quantity}
    
        def __len__(self):
            """総商品種類数"""
            return len(self._items)
    
        def __getitem__(self, product):
            """カート[商品] → 数量"""
            return self._items.get(product, 0)
    
        def __setitem__(self, product, quantity):
            """カート[商品] = 数量"""
            if quantity <= 0:
                if product in self._items:
                    del self._items[product]
            else:
                if quantity > product.stock:
                    raise ValueError(f"在庫不足: {product.name} (在庫: {product.stock})")
                self._items[product] = quantity
    
        def __delitem__(self, product):
            """del カート[商品]"""
            if product in self._items:
                del self._items[product]
    
        def __contains__(self, product):
            """商品 in カート"""
            return product in self._items
    
        def __iter__(self):
            """イテレーションサポート"""
            return iter(self._items.items())
    
        def __add__(self, other):
            """カート合併"""
            if not isinstance(other, ShoppingCart):
                return NotImplemented
    
            new_cart = ShoppingCart()
            new_cart._items = self._items.copy()
    
            for product, qty in other:
                new_cart[product] = new_cart[product] + qty
    
            return new_cart
    
        def __iadd__(self, product_tuple):
            """カート += (商品, 数量)"""
            product, quantity = product_tuple
            self[product] = self[product] + quantity
            return self
    
        def __call__(self):
            """カート() → 合計計算"""
            return sum(product.price * qty for product, qty in self)
    
        def __str__(self):
            """ユーザー向け表現"""
            if not self._items:
                return "🛒 カートは空です"
    
            lines = ["🛒 ショッピングカート:"]
            for product, qty in sorted(self._items.items()):
                subtotal = product.price * qty
                lines.append(f"  • {product.name} x {qty} = {subtotal:,}円")
            lines.append(f"  💰 合計: {self():,}円")
            return "\n".join(lines)
    
        def __repr__(self):
            """開発者向け表現"""
            return f"ShoppingCart(items={len(self)}, total={self():,}円)"
    
    # 使用例
    laptop = Product("ノートPC", 150000, stock=10)
    mouse = Product("マウス", 3000, stock=50)
    keyboard = Product("キーボード", 8000, stock=30)
    
    # ショッピングカート作成
    cart = ShoppingCart()
    
    # 商品追加(複数の方法)
    cart[laptop] = 1
    cart[mouse] = 2
    cart += (keyboard, 1)
    
    print(cart)
    print()
    
    # カート照会
    print(f"ノートPC数量: {cart[laptop]}")
    print(f"マウス含む? {mouse in cart}")
    print(f"総商品種類: {len(cart)}")
    print()
    
    # 合計計算(呼び出し可能オブジェクト)
    print(f"合計金額: {cart():,}円")

    実行結果:

    🛒 ショッピングカート:
      • キーボード x 1 = 8,000円
      • ノートPC x 1 = 150,000円
      • マウス x 2 = 6,000円
      💰 合計: 164,000円
    
    ノートPC数量: 1
    マウス含む? True
    総商品種類: 3
    
    合計金額: 164,000円

    💡 実践のコツと注意点

    Tip 1:__str__と__repr__ 両方実装する

    ユーザー向けと開発者向けの表現を両方提供すればデバッグが楽になります。

    class Point:
        def __str__(self):
            return f"({self.x}, {self.y})"  # ユーザー向け
    
        def __repr__(self):
            return f"Point(x={self.x}, y={self.y})"  # 開発者向け

    Tip 2:コンテキストマネージャーでリソース管理

    ファイル、ネットワーク接続などは必ずコンテキストマネージャーで管理しましょう。

    with MyResource() as resource:
        resource.use()
    # 自動的にクリーンアップ

    Tip 3:演算子オーバーロードは直感的に

    予測可能な動作で実装し、過度なオーバーロードは避けましょう。

    # ✅ 直感的
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    # ❌ 混乱する
    def __add__(self, other):
        return Vector(self.x * other.x, self.y * other.y)  # +なのに掛け算?

    Tip 4:特殊メソッドチートシート

    生成と消滅

    • `__init__(self, ...)`: コンストラクタ

    • `__del__(self)`: デストラクタ

    文字列表現

    • `__str__(self)`: `str(obj)`, `print(obj)`

    • `__repr__(self)`: `repr(obj)`, インタプリタ出力

    • `__format__(self, spec)`: `f"{obj:spec}"`

    呼び出しとコンテキスト

    • `__call__(self, ...)`: `obj()`

    • `__enter__(self)`: `with obj:` 開始

    • `__exit__(self, ...)`: `with obj:` 終了

    イテレーション

    • `__iter__(self)`: `iter(obj)`

    • `__next__(self)`: `next(obj)`

    コンテナ

    • `__len__(self)`: `len(obj)`

    • `__getitem__(self, key)`: `obj[key]`

    • `__setitem__(self, key, value)`: `obj[key] = value`

    • `__delitem__(self, key)`: `del obj[key]`

    • `__contains__(self, item)`: `item in obj`

    算術演算

    • `__add__(self, other)`: `obj + other`

    • `__sub__(self, other)`: `obj - other`

    • `__mul__(self, other)`: `obj * other`

    • `__truediv__(self, other)`: `obj / other`

    比較演算

    • `__eq__(self, other)`: `obj == other`

    • `__lt__(self, other)`: `obj < other`

    • `__gt__(self, other)`: `obj > other`

    • `__le__(self, other)`: `obj <= other`

    • `__ge__(self, other)`: `obj >= other`

    単項演算

    • `__neg__(self)`: `-obj`

    • `__pos__(self)`: `+obj`

    • `__abs__(self)`: `abs(obj)`

    ハッシュとブール

    • `__hash__(self)`: `hash(obj)`

    • `__boo__l(self)`: `bool(obj)`, `if obj:`


    🧪 練習問題

    問題1:スマート温度クラス

    摂氏と華氏を自動変換し、比較可能な「Temperature」クラスを作成してください。

    要件:

    • 摂氏温度で初期化

    • __str__で "25.0°C (77.0°F)" 形式出力

    • __repr__で再生成可能な形式

    • __format__で 'C' または 'F' フォーマットサポート

    • 比較演算子(<、>、== )サポート

    • 算術演算(+、-)サポート

    💡 ヒント

    • @total_orderingデコレータで`__eq__`と`__lt__`のみ実装すれば他の比較演算子は自動生成

    • 摂氏→華氏:celsius * 9/5 + 32

    • __format__でformat_specパラメータをチェック


    ✅ 解答

    from functools import total_ordering
    
    @total_ordering
    class Temperature:
        """スマート温度クラス"""
        def __init__(self, celsius):
            self.celsius = celsius
    
        @property
        def fahrenheit(self):
            """華氏温度"""
            return self.celsius * 9/5 + 32
    
        def __str__(self):
            """ユーザー向け表現"""
            return f"{self.celsius:.1f}°C ({self.fahrenheit:.1f}°F)"
    
        def __repr__(self):
            """開発者向け表現"""
            return f"Temperature({self.celsius})"
    
        def __format__(self, spec):
            """カスタムフォーマット"""
            if spec == 'C':
                return f"{self.celsius:.1f}°C"
            elif spec == 'F':
                return f"{self.fahrenheit:.1f}°F"
            else:
                return str(self)
    
        def __eq__(self, other):
            if not isinstance(other, Temperature):
                return NotImplemented
            return abs(self.celsius - other.celsius) < 0.01
    
        def __lt__(self, other):
            if not isinstance(other, Temperature):
                return NotImplemented
            return self.celsius < other.celsius
    
        def __add__(self, other):
            """温度足し算"""
            if isinstance(other, Temperature):
                return Temperature(self.celsius + other.celsius)
            return Temperature(self.celsius + other)
    
        def __sub__(self, other):
            """温度引き算"""
            if isinstance(other, Temperature):
                return Temperature(self.celsius - other.celsius)
            return Temperature(self.celsius - other)
    
    # テスト
    t1 = Temperature(25)
    t2 = Temperature(30)
    
    print(t1)                    # 25.0°C (77.0°F)
    print(repr(t1))              # Temperature(25)
    print(f"{t1:C}")             # 25.0°C
    print(f"{t1:F}")             # 77.0°F
    
    print(f"\nt2 > t1: {t2 > t1}")  # True
    
    temps = [t2, t1, Temperature(20)]
    print(f"\nソート後: {sorted(temps)}")


    📝 今日学んだ内容のまとめ

    `__str__`

    • 目的:ユーザーフレンドリーな文字列

    • 例:print(obj)

    `__repr__`

    • 目的:開発者向け表現

    • 例:デバッグ

    `__add__`

    • 目的:+演算子

    • 例:obj1 + obj2

    `__len__`

    • 目的:len()関数

    • 例:len(obj)

    `__getitem__`

    • 目的:インデックス

    • 例:obj[key]

    `__iter__`

    • 目的:繰り返し可能

    • 例:for item in obj

    `__call__`

    • 目的:呼び出し可能

    • 例:obj()

    `__enter__/__exit__`

    • 目的:コンテキストマネージャー

    • 例:with obj:

    特殊メソッド作成ガイド

    ✅ 推奨:

    • __str__:ユーザーが読みやすい形式

    • __repr__:eval(repr(obj)) == obj 原則

    • 演算子オーバーロード:直感的で予測可能に

    • コンテナ:__len__、__getitem__を一緒に実装

    ❌ 注意:

    • 過度な演算子オーバーロード

    • 予想外の動作

    • 標準プロトコル違反


    🔗 関連資料


    📚 前回の学習

    Day 38:ポリモーフィズム(Polymorphism)⭐⭐⭐⭐

    前回は、ポリモーフィズムの概念、ダックタイピング(Duck Typing)、演算子オーバーロード、抽象基底クラス(ABC)を学びました!

    📚 次回の学習

    Day 40:ミニプロジェクト4:図書管理システム⭐⭐⭐⭐(準備中)

    次回は、クラス、継承、カプセル化、ポリモーフィズム総合活用、特殊メソッドでユーザーフレンドリーなインターフェース実装、実践図書管理システム完成でPhase 4最終プロジェクトを進めます!

    📚 シリーズをまとめて読む

    Python 100日チャレンジの全記事は、
    マガジン「Python 100日チャレンジ」 でまとめて読めます 😊
    よろしければ、フォローしていただけると嬉しいです!


    🚀 遅いと思った時が一番早い時期です!🚀
    Day 39/100 | Phase 4:オブジェクト指向プログラミング | #100DaysOfPython

    よんよんわれ
     
     
    ソフトウェアエンジニアです。 ものづくりが好きで、プライベートでも複数のサイドプロジェクトに取り組んでいます。 最近は、AIと自動化を活用したサービス開発に力を入れています。 Note、Xなどでお友達になっていただけたら嬉しいです☺️

    あなたへのおすすめ