Date: February 7th 2016
Last updated: February 7th 2017

Composition is similar to inheritance. Composition is used for object associations with a "has a" relationship. For example, Dog has an association with Animal (also see inheritance). The major difference in the code below from what you might see in an example of inheritance is that "Dog" doesnt inherit from "Animal" (i.e. Dog inherits from object, not Animal). Instead we instantiate the Animal class when Dog is created. This is seems a little like blending classes together and in my mind forces the responsibility of the developer to specify the interaction between methods.


class Animal(object):
    tell an animal to make a sound
    def vocalise(self):
        return True

class Dog(object):
    Make a dog bark by responding to a cue from Animal class

    # Initialise association to Animal class
    def __init__(self):
        # Dog has a relationship with Animal
        self.vocal = Animal() 

    def gaurd(self):
        # use Animal.vocalise method
        if self.vocal.vocalise():
            return 'bark bark bark'

rover = Dog()
#returns: 'bark bark bark'

#returns: AttributeError: 'Dog' object has no attribute 'vocalise'

# returns: <bound method Animal.vocalise of <__main__.Animal object at 0x7f8e9fb47490>>

#returns: True

results matching ""

    No results matching ""