상세 컨텐츠

본문 제목

Protocols

Python

by techbard 2024. 12. 20. 16:13

본문

반응형
# Duck Typing with Protocols
# ==========================
# Duck Typing is a powerful feature of Python
# that allows us to write flexible code by focusing
# on the behavior of objects, not their type.

from typing import Protocol

class Flyer(Protocol):
    def fly(self) -> str: ...

class Bird:
    def fly(self) -> str:
        return 'Bird is flying'

class Airplane:
    def fly(self) -> str:
        return 'Airplane is flying'

def lift_off(flyer: Flyer):
    print(flyer.fly())

bird = Bird()
airplane = Airplane()
lift_off(bird)
lift_off(airplane)

# Output:
Bird is flying
Airplane is flying
반응형

관련글 더보기

댓글 영역