Skip to content

Instantly share code, notes, and snippets.

@AlphaSheep
Created October 13, 2023 18:21
Show Gist options
  • Save AlphaSheep/cc79963edc8152603cfad6673a37c426 to your computer and use it in GitHub Desktop.
Save AlphaSheep/cc79963edc8152603cfad6673a37c426 to your computer and use it in GitHub Desktop.
Composition over Inheritance and the AI Generated Code
class SwimmingAbility:
def swim(self, name, message):
print(f"{name} {message}")
class Duck:
def __init__(self, name):
self.name = name
self.swimming_ability = SwimmingAbility()
def swim(self):
self.swimming_ability.swim(self.name, "paddles furiously...")
class Elephant:
def __init__(self, name):
self.name = name
self.swimming_ability = SwimmingAbility()
def swim(self):
self.swimming_ability.swim(self.name, "is actually just walking on the bottom...")
if __name__ == "__main__":
duck = Duck("Sir Quacks-a-lot")
ellie = Elephant("Ellie BigEndian")
duck.swim()
ellie.swim()
from abc import ABC, abstractmethod
class SwimmingAnimal(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def swim(self):
raise NotImplementedError
class Duck(SwimmingAnimal):
def swim(self):
print(f"{self.name} paddles furiously...")
class Elephant(SwimmingAnimal):
def swim(self):
print(f"{self.name} is actually just walking on the bottom...")
def main():
duck = Duck("Sir Quacks-a-lot")
ellie = Elephant("Ellie BigEndian")
duck.swim()
ellie.swim()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment