Skip to content

Instantly share code, notes, and snippets.

@asalt
Created April 19, 2025 03:59
Show Gist options
  • Select an option

  • Save asalt/9970458b0e16c46daafd8856ecded880 to your computer and use it in GitHub Desktop.

Select an option

Save asalt/9970458b0e16c46daafd8856ecded880 to your computer and use it in GitHub Desktop.
class Thing:
def speak(self) -> str:
raise NotImplementedError("Things don't inherently speak.")
class Rock(Thing):
def speak(self, msg):
return ValueError("Rocks cannot speak")
class Plant(Thing):
def speak(self) -> str:
raise ValueError("Plants can't speak")
class Animal(Thing):
def speak(self) -> str:
return "Some generic animal noise"
class Dog(Animal):
def speak(self) -> str:
return "Woof!"
class Cat(Animal):
def speak(self) -> str:
return "Meow!"
class Human(Animal):
def speak(self, message):
return message
class Female(Human):
# no need to redefine "speak". show this in example
def spawn(self, other=None):
if other is None:
raise ValueError("Cannot spawn with only {self}")
class PollinatingPlant(Plant):
# no need to redefine "speak". show this in example
def spawn(self, other=None):
if other is None:
return new(self)
else:
return mate(other)
def mate(self, obj):
print(f"{self} is mating with {obj}")
return self._new()
def _new(self): # the leading _ indicates "private" method
print("🌿 A new plant has been spawned!")
return PollinatingPlant()
## ==========
class Female(Human):
gender = 'f'
def spawn(self, other=None):
if other is None:
raise ValueError("Cannot spawn with only {self}")
if other.gender == 'f':
raise ValueError("Cannot spawn with same {self.gender}")
if other.gender == 'm':
return self.mate(other)
def mate(self, obj):
... # not implemented
return self
class Female(Human):
gender = "f"
def spawn(self, other=None):
if other is None:
raise ValueError(f"Cannot spawn with only {self}")
if not isinstance(other, Human):
raise TypeError(f"Can only spawn with another Human, got {type(other).__name__}")
if other.gender == self.gender:
raise ValueError("Gender mismatch: cannot spawn with same gender.")
return self.mate(other)
def mate(self, other):
print(f"{self} is spawning with {other}")
return Human()
class Male(Female):
gender = "m"
if __name__ == "__main__":
mom = Female()
dad = Male()
kid = mom.spawn(dad)
print(isinstance(kid, Human)) # True
print(kid.speak(f"I'm the product of {mom} and {dad}"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment