Preview

07 - Inheritance

 1. Inheritance is the process by which a "child" class derives the data and behavior of a "parent" class
You can find the full (free) series on inheritance and OOP in python on www.teachyourselfpython.com

  TRUE

  FALSE

 2. Another way of thinking of inheritance is a way of arranging objects in a hierarchy from the most _________________________

  None of the above

  general to the most specific

  expensive to the least costly

  specific to the most general

 3. An object which inherits from another object is considered to be a _____type of that object

  private

  inheritance-band

  sub

  mask

 4. We also often say that a class is a subclass or child class of a class from which it inherits, or that the other class is its superclass or ________________

  pivotal class

  encapsulated class

  parent class

  node class

 5. We can refer to the most generic class in the hierarchy as a ________________

  base class

  root node

  object class

  inherited class

 6. Inheritance is also a way of ______________

  creating a subclass in which we partially override some of the parent classes behaviour

  using the existing class with its attributes and methods but also adding functionality.

   reusing existing code easily.

  All of the above are valid

 7. Analyse the following code. Name the base class and the sub class.
class Person:
    def __init__(self, name, surname, number):
        self.name = name
        self.surname = surname
        self.number = number


class Student(Person):
    UNDERGRADUATE, POSTGRADUATE = range(2)

    def __init__(self, student_type, *args, **kwargs):
        self.student_type = student_type
        self.classes = []
        super(Student, self).__init__(*args, **kwargs)

    def enrol(self, course):
        self.classes.append(course)


class StaffMember(Person):
    PERMANENT, TEMPORARY = range(2)

    def __init__(self, employment_type, *args, **kwargs):
        self.employment_type = employment_type
        super(StaffMember, self).__init__(*args, **kwargs)


class Lecturer(StaffMember):
    def __init__(self, *args, **kwargs):
        self.courses_taught = []
        super(Lecturer, self).__init__(*args, **kwargs)

    def assign_teaching(self, course):
        self.courses_taught.append(course)


jane = Student(Student.POSTGRADUATE, "Ruth", "Marvin", "SMTJNX045")
jane.enrol(a_postgrad_course)

bob = Lecturer(StaffMember.PERMANENT, "Jonathan", "Peter", "123456789")
bob.assign_teaching(an_undergrad_course)

  The base class doesn't exist, as this example uses inheritance

  The base class is 'Person' and the subclass is 'StaffMember'

  The base class is 'StaffMember' and the subclass is 'Person'

  There are two base classes - as there is no inheritance in this example

 8. The following code demonstrates _____________ inheritance
class Course:
    name="Python Course"
    contactWebsite="www.teachyourselfpython.com"

    def contactDetails(self):
        print("To contact us, simply go to", self.contactWebsite)

#Course is the base/parent class, and the OOP Class is the child or derived class.
class OOPCourse(Course): #this inherits the attributes and methods of the class Course
#the OOP class can have its own attributes and methods in addition to derived attributes and methods
    def __init__(self):
        self.description="Course on OOP Fundamentals"
        self.trainer="Mrs TeachYourselfPython herself"

    def trainerDetails(self):
        print("This Course is about:",self.description, "and is run by:", self.trainer)



#===================DEMONSTRATION OF ____________???? INHERITANCE =================
course1=OOPCourse() #creating an object for the class OOPCourse
#use the object above to call the methods
course1.contactDetails()
course1.trainerDetails()

  multiple

  None of the above

  single

  multi-level

 9. Real world example for ______: If your father played chess, you inherited this ability, but you also like to dance. Your son, if you have one, could inherit both your father's ability to play chess as well as your dance moves!

  None of the above

  multi-level

  multiple

  single

 10. _________inheritance is when a child class derives attributes and methods from more than one parent class

  None of the above

  single

  multiple

  multi-level

 11. What is the output of the following piece of code?
class Test:
    def __init__(self):
        self.x = 0
class Derived_Test(Test):
    def __init__(self):
        self.y = 1
def main():
    b = Derived_Test()
    print(b.x,b.y)
main()

  Error - because the object has not been created correctly.

  AttributeError: 'Derived_Test' object has no attribute 'x'

  0,1

  0,0

 12. Analyse this code that includes inheritance. What is the output?
class A():
    def disp(self):
        print("A disp()")
class B(A):
    pass
obj = B()
obj.disp()

  A disp()

  Invalid syntax for inheritance

  Error because no arguments have been passed

  Nothing is printed

 13. Predict the output here - note the inheritance that is taking place.
class Test:
    def __init__(self):
        self.x = 0
class Derived_Test(Test):
    def __init__(self):
        Test.__init__(self)
        self.y = 1
def main():
    b = Derived_Test()
    print(b.x,b.y)
main()

  Error - because B inherits from A, but the variable x is not inherited.

  0,1

  0,0

  Error - invoking method is incorrect

 14. Predict the output of the following code.
class A:
    def __init__(self, x= 1):
        self.x = x
class der(A):
    def __init__(self,y = 2):
        super().__init__()
        self.y = y
def main():
    obj = der()
    print(obj.x, obj.y)
main()

  1,0

  1,1

  1,2 because x = 1 and y = 2 and the invoking method has been properly implemented

  The program runs fine but nothing is printed

 15. Predict the output.
class A:
    def one(self):
        return self.two()
 
    def two(self):
        return 'A'
 
class B(A):
    def two(self):
        return 'B'
obj1=A()
obj2=B()
print(obj1.two(),obj2.two())

  An exception is thrown

  BB

  AA

  AB

 16. The following is an example of:
class A():
    pass
class B():
    pass
class C(A,B):
    pass

  None of the above

  multiple inheritance

  multilevel inheritance

  single inheritance

 17. In some languages it is possible to create a class which can’t be instantiated.
 That means that we can’t use this class directly to create an object – we can only inherit from the class, and use the subclasses to create objects.

  FALSE

  TRUE

 18. In Python we can’t prevent anyone from instantiating a class, but we can create something similar to an ____________ by using NotImplementedError inside our method definitions.

  abstract class

  base class

  inherited class

  known class

 19. Look closely here for any evidence of encapsulation. Predict the output of this program.
class A:
     def __init__(self):
         self.__i = 1
         self.j = 5
 
     def display(self):
         print(self.__i, self.j)
class B(A):
     def __init__(self):
         super().__init__()
         self.__i = 2
         self.j = 7  
c = B()
c.display()

  2,7, because the class B overrides the variable assignments

  2,5 because the first variable will be overwritten but not the second

  1,7 because ay change made in variable i isn’t reflected as it is a private member of the superclass

  1,5 because the super class A will retain its values for i and j

 20. Method issubclass() returns True if a class is a subclass of another class and False otherwise.

  FALSE

  TRUE