Skip to content

Instantly share code, notes, and snippets.

@jaycosaur
Last active August 10, 2020 06:35
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jaycosaur/48d253f2bcee8ff5e10122ca45688228 to your computer and use it in GitHub Desktop.
Composable types [python-ABC] - Typescript to Python field guide
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