Saturday, 13 February 2016

Inheritance and Composition

   
 The OOP allows us to create a number of classes (data types) for various purposes (i.e., implement a class through defining the attribute(s)) and the operations on the data within each class (i.e., define methods for a class). However, if there is no link between the classes, the class implementation is meaningless at all. It's pretty rare to use a single class even for a simple function. The link between the classes is either composition (horizontal link) or inheritance (vertical link).

 1. Composition

When a class is defined, it is independent to other classes. But the composition allows it to call the abstract object/instance of other classes and/or to define object/instance of other classes. As a result, this class is able to access to the object's attributes and methods defined by other classes. The composition is particularly helpful to simplify the design and implementation of an ADT class.
           
For example, we need an ADT class to register a student to a course. Before implementing the ADT class StuCourRegistry, we firstly implement two meaningful classes Student and Course. Hence the StuCourRegistry will be able to call the abstract object of Student and Course, which makes us focus on how to process the data without worrying about what is the data  and then develop complicated methods.
       
class Student():                 
                def __init__(self,_id=' ',name=' ',num=0):
                    self._id, self.name, self.num=str(_id), str(name), int(num)
       
                def __hash__(self):  # this method makes the object be elements of dict and set.
                    return hash((self._id, self.name, self.num))   
       
                def __eq__(self,other):
                    return type(self)==type(other) and (self._id, self.num)==(other._id, other.num)

class Course():                         
                def __init__(self,name=' ',_id=' ',dept=' '):
                    self.name, self._id,self.dept=str(name), str(_id), str(dept)       
   
                def __hash__(self):
                    return hash((self.name,self._id,self.dept))
       
                def __eq__(self,other):
                    return type(self)==type(other) and self._id==other._id
                   
class StuCourRegistry():                        
                def __init__(self,registry={}):
                    self.registry=registry
                                        
                def add_cour(self,course):  # course is the object of Course.
                    if not course in self.registry.keys():       
                        self.registry[course]=set() # set() just contains Unique data.
                    else:
                        raise Exception('Duplicate Course!!!')           
                                                                
                def add_stu(self,course,student):
                     # course and student are the object of Course and Student.
                    if course in self.registry.keys():         
                        self.registry[course].add(student)
                    else:
                        raise Exception("The course is NOT available!!!")                      
                                                        
                 def count_stu_for_dept(self,dept):
                    stu_dept=set()
                    for item in self.registry.items():
                        if item[0].dept==dept: # the object of Course has the attribute "dept".
                            stu_dept=stu_dept.union(item[1])
                     for s in stu_dept:
                         print(s.name)
                     return len(stu_dept)
               
2. Inheritance

When a class (called subclass) has a vertical link with another class (called super class), this link is called inheritance that allows the subclass to own everything (attributes and methods) defined by the super class. Inheritance, however, doesn't forbid the subclass having its own things and even allow it to rewrite the inherited attributes and methods. Inheritance saves a lot of time of writing duplicate codes and makes the code maintenance much easier because any change on the super class is automatically applied to the sub-classes. As a result, we create a super class mainly not for substantiation (i.e., creating objects of super class) but for the inheritance by the sub-classes.

The creation of a super class relies on how many common features the sub-classes share. For example, Python has a built_in class 'object' that is the super class of every built_in or self_defined class. The 'object' defines the methods used by every class like __init__,__repre__,__str__,
 __eq__ and __dir__. Notice when creating a subclass, we usually override the methods _init__,__str__,__repr__, and __eq__ but remains the method __dir__.

Now let's see another example. We create two sub-classes of the Stack. The 1st has nothing but inherits everything from Stack. But the 2nd overrides the Stack's attribute and related methods meanwhile inheriting other methods.
           
class Stack:   
                   def __init__(self, content=[]):
                        self.content=[]
       
                    def push(self,data):
                        self.content.append(data)
       
                    def pop(self):
                        try:
                            return self.content.pop()
                        except IndexError:
                            print('Empty Stack')
                            return None
   
                    def is_empty(self):
                        return len(self.content)==0
                   
class NumStack(Stack):  # explicitly declare the inheritance.
                    pass

class UniqueNumStack(Stack):   
                    def __init__(self,content=set()):   # override the inherited attribute
                        self.content=content
       
                    def push(self,data): # override the inherited method
                        self.content.add(data)
       
                    def pop(self): # override the inherited method
                        if not Stack.is_empty(self): # load the inherited method
                            num = list(self.content)[-1]
                            self.content.discard(num)
                            return num
                        else:
                            return None


End of this post

No comments:

Post a Comment