# 第25章示例:魔法方法 __str__ / __eq__ / __add__ / __del__

# --- 1. __str__ 打印美化 ---
class Account:
    def __init__(self, holder, balance=0):
        self.holder = holder
        self._balance = balance

    def __str__(self):
        return f"账户[{self.holder}]:{self._balance}元"

    def __add__(self, other):
        """两个账户合并(家庭共同账户)"""
        return Account(self.holder + "+" + other.holder,
                       self._balance + other._balance)

    def __eq__(self, other):
        if not isinstance(other, Account):
            return False
        return self._balance == other._balance

a1 = Account("小明", 100)
a2 = Account("小红", 100)
print(a1)                 # 账户[小明]:100元
print(a1 == a2)           # True(余额相同)
merged = a1 + a2
print(merged)             # 账户[小明+小红]:200元

# --- 2. __del__ 销毁时清理(了解) ---
class FileWrapper:
    def __init__(self, name):
        self.name = name
        print(f"打开文件 {name}")

    def __del__(self):
        print(f"关闭文件 {self.name}")

fw = FileWrapper("data.txt")
print("工作中...")
