Inheritance, another key principle of object-oriented design, plays a big role in implementing polymorphic behavior. Given a class hierarchy, the topmost classes will often define a base interface for behavior. These base methods often go unimplemented. It is the classes that inherit from the base class that are responsible for implementing the behavior. This means that subclasses even further down the inheritance hierarchy can also define this behavior.
Any descendants of the base class can be used in the same context and will behave as expected. Below is an example illustrating the difference between inheriting a method and providing an implementation for it and inheriting an already-defined method.
#Example; Polymorphism and inheritance.
#Do imports.
import uuid
import timeit
#Simple person class.
class Person(object):
#Constructor. Initialize the data.
def __init__(self):
self.data={"first_name":"FirstName",\
"last_name":"LastName",\
"id":uuid.uuid1()}
#Return the first name.
def get_first_name(self):
return "first_name_%s"%(self.data["first_name"])
#Return the last name.
def get_last_name(self):
return "last_name_%s"%(self.data["last_name"])
#Return the id.
def get_id(self):
raise NotImplementedError
#Simple manager class that extends Person.
class Manager(Person):
#Constructor. Initialize the Person class.
def __init__(self):
Person.__init__(self)
#Return the manager id.
def get_id(self):
return "manager_%s"%(self.data["id"])
#Simple employee class that extends Person.
class Employee(Person):
#Constructor. Initialize the Person class.
def __init__(self):
Person.__init__(self)
#Return the employee id.
def get_id(self):
return "employee_%s"%(self.data["id"])
#Main.
if __name__=="__main__":
#Employee.get_id() timer.
t_employee_get_id=timeit.Timer("Employee().get_id()",\
setup="from __main__ import Employee")
#Manager.get_id() timer.
t_manager_get_id=timeit.Timer("Manager().get_id()",\
setup="from __main__ import Manager")
#Employee.get_first_name() timer.
t_employee_get_first_name=timeit.Timer("Employee().get_first_name()",\
setup="from __main__ import Employee")
#Manager.get_first_name() timer.
t_manager_get_first_name=timeit.Timer("Manager().get_first_name()",\
setup="from __main__ import Manager")
#Display the results.
print "Employee Get ID: ", t_employee_get_id.timeit(10000)
print "Manager Get ID: ", t_manager_get_id.timeit(10000)
print "Employee Get First Name: ", t_employee_get_first_name.timeit(10000)
print "Manager Get First Name: ", t_manager_get_first_name.timeit(10000)
No comments :
Post a Comment