Lecture #12
UNIT-III
OOPS
Inheritance
• Inheritance is an important aspect of the object-oriented paradigm.
Inheritance provides code reusability to the program because we can use
an existing class to create a new class instead of creating it from scratch.
• In inheritance, the child class acquires the properties and can access all
the data members and functions defined in the parent class. A child class
can also provide its specific implementation to the functions of the parent
class. In this section of the tutorial, we will discuss inheritance in detail.
• In python, a derived class can inherit base class by just mentioning the
base in the bracket after the derived class name. Consider the following
syntax to inherit a base class into the derived class.
Inheritance
Single Inheritance Example
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
[Link]()
[Link]()
Multiple Inheritance Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print([Link](10,20))
print([Link](10,20))
print([Link](10,20))
Multi Level Inheritance Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
[Link]()
[Link]()
[Link]()
Overriding Methods
• Polymorphism: It is a property of an object which allows it to take multiple forms.
• Polymorphism is of two types:
• Compile-time Polymorphism: method overloading
• Run-time Polymorphism: method Overriding
• You can always override your parent class methods. One reason for overriding parent's methods is because you
may want special or different functionality in your subclass.
Overriding Methods Example
class Parent: # define parent class
def myMethod(self):
print ("Calling parent method")
class Child(Parent): # define child class
def myMethod(self):
print ("Calling child method")
c = Child() # instance of child
[Link]() # child calls overridden method
Base Overloading Methods
[Link]. Method, Description & Sample Call
1 __init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call : obj = className(args)
2 __del__( self )
Destructor, deletes an object
Sample Call : del obj
3 __repr__( self )
Evaluable string representation
Sample Call : repr(obj)
4 __str__( self )
Printable string representation
Sample Call : str(obj)
5 __cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)
Overloading Operators
• Suppose you have created a Vector class to represent two-dimensional vectors, what
happens when you use the plus operator to add them? Most likely Python will yell at you.
• You could, however, define the __add__ method in your class to perform vector addition
and then the plus operator would behave as per expectation
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
Data Hiding
• An object's attributes may or may not be visible outside the class definition. You
need to name attributes with a double underscore prefix, and those attributes then
are not be directly visible to outsiders.
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print (self.__secretCount)
counter = JustCounter()
[Link]()
[Link]()
print (counter.__secretCount)
When the above code is executed, it produces the following result −
1
2
Traceback (most recent call last): File "[Link]", line 12, in
<module> print counter.__secretCount AttributeError:
JustCounter instance has no attribute '__secretCount'
• Python protects those members by internally changing the name to
include the class name. You can access such attributes
as object._className__attrName. If you would replace your last line
as following, then it works for you −
• .........................
• Print( counter._JustCounter__secretCount)
Function Overloading
• In Python you can define a method in such a way that there are multiple ways to call
it. Depending on the function definition, it can be called with zero, one, two or more
parameters. This is known as method overloading.
• In the given code, there is a class with one method sayHello(). We rewrite as shown
below. The first parameter of this method is set to None, this gives us the option to
call it with or without a parameter.
• An object is created based on the class, and we call its method using zero and one
parameter. To implement method overloading, we call the method sayHello() in two
ways: 1. [Link]() and [Link]('Rambo')
• We created a method that can be called with fewer arguments than it is defined to
allow. We are not limited to two variables, given method can have more variables
which are optional.
Function Overloading Example
class Human:
def sayHello(self, name=None):
if name is not None:
print ('Hello ' + name)
else:
print ('Hello ')
obj = Human()
print([Link]())
print([Link]('Rambo'))
More Details:
[Link]
[Link]
Difference between Method Overloading and Method Overriding in Python
[Link] Method Overloading Method Overriding
In the method overloading, methods or functions
Whereas in the method overriding, methods or functions
1. must have the same name and different
must have the same name and same signatures.
signatures.
Method overloading is a example of compile time Whereas method overriding is a example of run time
2.
polymorphism. polymorphism.
In the method overloading, inheritance may or Whereas in method overriding, inheritance always
3.
may not be required. required.
Method overloading is performed between Whereas method overriding is done between parent
4.
methods within the class. class and child class methods.
It is used in order to add more to the behavior of Whereas it is used in order to change the behavior of
5.
methods. exist methods.
In method overloading, there is no need of more Whereas in method overriding, there is need of at least
6.
than one class. of two classes.
Questions1(Account Class)
• Design the class name account that contains:
– A private id for account
– A private balance for account
– A private intrate for annual interest rate
– A constructor that creates an account with specified id, initial balance and interest rate.
– A method name getmonthlyinterestrate() that return monthly interest rate.
– A method name checkbalance() that return balance amount from the account.
– A method name withdraw() that withdraws a specified amount from the account.
– A method name deposite() that deposits a specified amount to the account.
== Create 10 accounts with initial balance 100 and rate of interest 4%.
==The system prompts the user to enter account ID, if it is correct open a main menu having chaises
1. Check balance, 2. withdraw, 3. deposit and 4. exit.
12/12/14