Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
66 lines (51 sloc) 1.53 KB
import os
class Dog(object):
def __init__(self): = "Dog"
def bark(self):
return "woof!"
class Cat(object):
def __init__(self): = "Cat"
def meow(self):
return "meow!"
class Human(object):
def __init__(self): = "Human"
def speak(self):
return "'hello'"
class Car(object):
def __init__(self): = "Car"
def make_noise(self, octane_level):
return "vroom%s" % ("!" * octane_level)
class Adapter(object):
Adapts an object by replacing methods.
dog = Dog
dog = Adapter(dog, dict(make_noise=dog.bark))
def __init__(self, obj, adapted_methods):
"""We set the adapted methods in the object's dict"""
self.obj = obj
def __getattr__(self, attr):
"""All non-adapted calls are passed to the object"""
return getattr(self.obj, attr)
def main():
objects = []
dog = Dog()
objects.append(Adapter(dog, dict(make_noise=dog.bark)))
cat = Cat()
objects.append(Adapter(cat, dict(make_noise=cat.meow)))
human = Human()
objects.append(Adapter(human, dict(make_noise=human.speak)))
car = Car()
car_noise = lambda : car.make_noise(3)
objects.append(Adapter(car, dict(make_noise=car_noise)))
for obj in objects:
print("A",, "goes", obj.make_noise())
if __name__ == "__main__":