Skip to content

Instantly share code, notes, and snippets.

@cawhitworth
Created May 15, 2014 14:50
Show Gist options
  • Save cawhitworth/ae442f299740ed4a0747 to your computer and use it in GitHub Desktop.
Save cawhitworth/ae442f299740ed4a0747 to your computer and use it in GitHub Desktop.
Composition and inheritance in Python (Smalltalk style)
class Base:
def mul(self, a, b):
return a * b
def add(self,a,b):
return a + b
class Derived(Base):
def sub(self,a,b):
return a - b
def div(self,a,b):
return a / b
class Composed:
def __init__(self):
self.base = Base()
def sub(self,a,b):
return a - b
def div(self,a,b):
return a / b
def __getattr__(self, name):
return getattr(self.base, name)
foo = Derived()
print(foo.sub(1,2))
print(foo.add(1,2))
bar = Composed()
print(bar.sub(1,2))
print(bar.add(1,2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment