Last active
August 10, 2020 06:35
-
-
Save jaycosaur/48d253f2bcee8ff5e10122ca45688228 to your computer and use it in GitHub Desktop.
Composable types [python-ABC] - Typescript to Python field guide
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from abc import ABC, abstractmethod | |
class Animal(ABC): | |
@property | |
@abstractmethod | |
def length(self) -> float: | |
... | |
@abstractmethod | |
def eat(self, food: str) -> None: | |
... | |
class Fish(Animal): | |
@abstractmethod | |
def swim(self, howLong: float) -> None: | |
... | |
# MyFish explicitly implements the Fish interface | |
class MyFish(Fish): | |
@property | |
def length(self) -> float: | |
return 12 | |
def eat(self, food: str) -> None: | |
print(f"Eating {food}") | |
def swim(self, howLong: float) -> None: | |
print(f"Swimming for {howLong}") | |
fish = MyFish() | |
def do_something_fishy(what: Fish): | |
what.eat("worms") | |
what.swim(what.length) | |
do_something_fishy(fish) # this is ok! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment