상속 비교와 문자열 표현

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 객체 지향 프로그래밍 입문

은행 계좌와 예금 계좌

BankAccount를 상속하는 SavingsAccount

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)
# 두 객체를 비교
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 객체 지향 프로그래밍 입문

Ayo berlatih!

Python 객체 지향 프로그래밍 입문

Preparing Video For Download...