Python 2.7.12 - Polymorphism Example

Here is a very practical Python polymorphism example that you might be able to relate to. I decided to do this one because I've been getting tired of seeing the typical textbook versions of polymorphism.

Here is the screenshot of the code that displays better than the text version that you can use to copy and paste.


Text version:

#!/usr/bin/python

def main():
    # Array of objects

    apps_to_be_deployed = [JavaApplicationDeployer('Offers microservice', '3'),            DotNetApplicationDeployer('Customers microservice', '5'),            JavaApplicationDeployer('Memberships microservice', '4')]

    for app in apps_to_be_deployed:
        print ('App name', app.name, 'Performed the deployment ... Platform AND Number of instances: ', app.perform_deployment())


# Define a class as ApplicationDeployerclass ApplicationDeployer:
    # Constructor of the class

    def __init__(self, name, number_of_instances):
        self.name = name
        self.number_of_instances = number_of_instances

    # Abstract method

    def perform_deployment(self):
        raise NotImplementedError("Sub-class must implement abstract method")


# Define a class as JavaApplicationDeployer and inherit ApplicationDeployer

class JavaApplicationDeployer(ApplicationDeployer):
    # Redefine method with same name as super class

    def perform_deployment(self):
        print("Setting up JAVA related dependencies...")
        return 'JAVA', self.number_of_instances


# Define a class as DotNetApplicationDeployer and inherit ApplicationDeployer

class DotNetApplicationDeployer(ApplicationDeployer):
    # Redefine method with same name as super class

    def perform_deployment(self):
        print("Setting up .NET related dependencies...")
        return 'DOT_NET', self.number_of_instances


if __name__ == "__main__": main()

Almir M.

No comments:

Post a Comment