ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • ABC vs Protocol
    python/응용 2023. 4. 1. 20:36

    ABC

    import abc
    
    
    # abc.ABC 를 상속받아 생성: Person 객체를 직접 생성 불가능하게 함
    class Person(abc.ABC):
        def __init__(self, age=1):
            self.age = age
    
        @abc.abstractmethod
        def drive(self):
            pass
    
    
    class Adult(Person):
        def drive(self):
            print("ok")
    
    
    person = Adult()
    person.drive()

     

    Protocol

    https://www.pythontutorial.net/python-oop/python-protocol/ 를 참고함

     

    from typing import Protocol
    
    
    ################################################################
    # Protocol 정의
    ################################################################
    class Item(Protocol):
        quantity: float
        price: float
    
    
    def calculate_total(items: list[Item]) -> float:
        return sum([item.quantity * item.price for item in items])
    
    
    ################################################################
    # 활용 하기 1
    ################################################################
    class Product:
        def __init__(self, name: str, quantity: float, price: float):
            self.name = name
            self.quantity = quantity
            self.price = price
    
    
    total = calculate_total([
        Product('A', 10, 150),
        Product('B', 5, 250)
    ])
    print(total)
    
    
    ################################################################
    # 활용 하기 2
    ################################################################
    class Stock:
        def __init__(self, product_name, quantity, price):
            self.product_name = product_name
            self.quantity = quantity
            self.price = price
    
    
    total = calculate_total([
        Stock('Tablet', 5, 950),
        Stock('Laptop', 10, 850)
    ])
    print(total)

    'python > 응용' 카테고리의 다른 글

    __slot__, __call__  (0) 2023.04.10
    yield from  (0) 2023.04.10
    ThreadPoolExecutor  (0) 2023.02.09
    AsyncIO  (0) 2022.10.29
    ProcessPoolExecutor  (0) 2022.10.29

    댓글

Designed by Tistory.