Created
May 15, 2014 14:50
-
-
Save cawhitworth/ae442f299740ed4a0747 to your computer and use it in GitHub Desktop.
Composition and inheritance in Python (Smalltalk style)
This file contains 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
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