継承の比較と文字列表現

Pythonによるオブジェクト指向プログラミング入門

George Boorman

Curriculum Manager, DataCamp

異なるクラスのオブジェクト比較

class Customer:
    def __init__(self, acc_id, name):
        self.acc_id, self.name = acc_id, name

    def __eq__(self, other):
        # 同じ属性を持ち、同じ型なら True を返す
        # and are of the same type
        return (self.acc_id == other.acc_id) and (self.name == other.name)\
            and (type(self) == type(other))
Pythonによるオブジェクト指向プログラミング入門

継承を伴うオブジェクトの比較

 

 

 

                               

    一方のオブジェクトが他方のクラスを「継承」している場合は?

Pythonによるオブジェクト指向プログラミング入門

銀行口座と貯蓄口座

貯蓄口座は銀行口座を継承

Pythonによるオブジェクト指向プログラミング入門

親/子クラスでの __eq__

class BankAccount:
    def __init__(self, number, balance=0):
        self.balance = balance
        self.number = number

    def withdraw(self, amount):
        self.balance -= amount 

    # number 属性が等しければ True を返す
    def __eq__(self, other):
        print("BankAccount __eq__() called")
        return self.number == other.number 
class SavingsAccount(BankAccount):
    def __init__(self, number, balance, interest_rate):
        BankAccount.__init__(self, number,
                             balance)
          self.interest_rate = interest_rate

    # number 属性が等しければ True を返す
    def __eq__(self, other):
        print("SavingsAccount __eq__() called")
        return self.number == other.number 
Pythonによるオブジェクト指向プログラミング入門

親子オブジェクトの比較

ba = BankAccount(123, 10000)
sa = SavingsAccount(456, 2000, 0.05)
# 2つのオブジェクトを比較
ba == sa
SavingsAccount __eq__() called
False
sa == ba
SavingsAccount __eq__() called
False
Pythonによるオブジェクト指向プログラミング入門

オブジェクトを印字する

class Customer:
    def __init__(self, name, balance):
        self.name, self.balance = name, balance 

cust = Customer("Maryam Azar", 3000)
print(cust)
<__main__.Customer at 0x1f8598e2240>




a_list = [1,2,3]
print(a_list)
[1, 2, 3]
Pythonによるオブジェクト指向プログラミング入門

__str__()

  • print(obj), str(obj)
print(np.array([1,2,3]))
[1 2 3]
str(np.array([1,2,3]))
'[1 2 3]'
  • 非公式、エンドユーザー向け
  • 文字列としての表現

__repr__()

  • repr(obj)、コンソール表示
repr(np.array([1,2,3]))
'array([1,2,3])'
np.array([1,2,3])
array([1, 2, 3])
  • 公式、開発者向け
  • 再現可能な表現
  • print() のフォールバック
Pythonによるオブジェクト指向プログラミング入門

実装: repr

class Customer:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance 

    def __repr__(self):

# name を '...' で囲む点に注意 return f"Customer('{self.name}', {self.balance})"
cust = Customer("Maryam Azar", 3000) # 暗黙に __repr__() が呼ばれる cust
Customer('Maryam Azar', 3000)
Pythonによるオブジェクト指向プログラミング入門

実装: str

class Customer:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
    def __str__(self):
        cust_str = f"""
        Customer:
            name: {self.name}
            balance: {self.balance}
            """
        return cust_str
cust = Customer("Maryam Azar", 3000)

# 暗黙に __str__() が呼ばれる
print(cust)
Customer:
  name: Maryam Azar
  balance: 3000
Pythonによるオブジェクト指向プログラミング入門

Passons à la pratique !

Pythonによるオブジェクト指向プログラミング入門

Preparing Video For Download...