Product SiteDocumentation Site

11.4. student_teacher.py

#!/usr/bin/env python

class Person(object):
    """
    Returns a ```Person``` object with given name.

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

    def get_details(self):
        "Returns a string containing name of the person"
        return self.name


class Student(Person):
    """
    Returns a ```Student``` object, takes 3 arguments, name, branch, year.
    
    """
    def __init__(self,name,branch,year):
        Person.__init__(self,name)
        self.branch = branch
        self.year = year

    def get_details(self):
        "Returns a string containing student's details."
        return "%s studies %s and is in %s year." % (self.name, self.branch, self.year)


class Teacher(Person):
    """
    Returns a ```Teacher``` object, takes a list of strings (list of papers) as
    argument.
    """    
    def __init__(self, name, papers):
        Person.__init__(self, name)
        self.papers = papers

    def get_details(self):
        return "%s teaches %s" % (self.name, ','.join(self.papers))


person1 = Person('Sachin')
student1 = Student('Kushal', 'CSE', 2005)
teacher1 = Teacher('Prashad', ['C', 'C++'])

print person1.get_details()
print student1.get_details()
print teacher1.get_details()


The output:
$ ./student_teacher.py 
Sachin
Kushal studies CSE and is in 2005 year.
Prashad teaches C,C++


In this example you can see how we called the __init__ method of the class Person in both Student and Teacher classes' __init__ method. We also reimplemented get_details() method of Person class in both Student and Teacher class. So, when we are calling get_details() method on the teacher1 object it returns based on the object itself (which is of teacher class) and when we call get_details() on the student1 or person1 object it returns based on get_details() method implemented in it's own class.