Composition

Composition is a property that is used to express a relationship between the different objects. The way this relationship is expressed in composition is by making an object an attribute of another object.

Python supports the concept of composition by allowing the programmer to build objects that can then be made part of other objects. For example, let's take a look at the following code snippet:

class MessageHandler:
__message_type = ['Error', 'Information', 'Warning', 'Debug']

def __init__(self, date_format):
self.date_format = date_format

def new_message(message, message_code, message_type='Information'):
if message_type not in self.__message_type:
raise Exception("Unable to handle the message type")
msg = "[{}] {}: {}".format(message_type, message_code, message)
return msg

class WatchDog:

def __init__(self, message_handler, debug=False):
self.message_handler = message_handler
self.debug = debug

def new_message(message, message_code, message_type):
try:
msg = self.message_handler.new_message(message, message_code, message_type)
except Exception:
print("Unable to handle the message type")
return msg

message_handler = MessageHandler('%Y-%m-%d')
watchdog = WatchDog(message_handler)

As we can see from the example, we have made the message_handler object an attribute of the watchdog object. This marks one of the ways through which we can achieve composition in Python.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.34.197