Professional Documents
Culture Documents
Experiment No: 6A: Neel Sanjay Bhatt Roll No:-07 SE Computer A
Experiment No: 6A: Neel Sanjay Bhatt Roll No:-07 SE Computer A
Experiment No: 6A: Neel Sanjay Bhatt Roll No:-07 SE Computer A
Roll No:-07
SE Computer A
Experiment No: 6A
AIM: A Python program to create a Bank class where deposits and withdrawals
can be handled by using instance methods
TOOLS USED: Python 3.4.3, Terminal
THEORY:
1)Explain Inheritance in Python with syntax
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 python, a derived class can inherit base class by just mentioning the base in the
bracket after the derived class name.
Syntax
1. class derived-class(base class):
2. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket.
Consider the following syntax.
Syntax
1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
2. <class - suite>
2)Explain what is constructor overriding and method overriding and how to
overcome
Method overriding:
Method overriding in action In Python method overriding occurs simply defining
in the child class a method with the same name of a method in the parent class.
When you define a method in the object you make the latter able to satisfy
that method call, so the implementations of its ancestors do not come in play.
Override means having two methods with the same name but doing different tasks.
It means that one of the methods overrides the other.
If there is any method in the superclass and a method with the same name in a
subclass, then by executing the method, the method of the corresponding class will
be executed.
Constructor Overriding:
When an instance of a class is initialized, the super-class state should be fully
initialized before it becomes visible to the subclass. Calling methods of the subclass
in the superclass' __init__ method violates this important invariant.
How to overcome Constructor overriding
Do not use methods that are subclassed in the construction of an object. For simpler
cases move the initialization into the superclass' __init__ method, preventing it being
overridden. Additional initialization of subclass should be done in
the __init__ method of the subclass. For more complex cases, it is advisable to use
a static method or function to manage object creation.
Alternatively, avoid inheritance altogether using composition instead
a)Single Inheritance in Python
Syntax
class derived-class(base class):
<class-suite>
1. >>> x=0
2. >>> class fruit:
3. def __init__(self):
4. global x
5. x+=1
6. print("I'm a fruit")
7. >>> class citrus(fruit):
8. def __init__(self):
9. super().__init__()
10. global x
11. x+=2
12. print("I'm citrus")
13. >>> x
1. >>> lime=citrus()
Output:
I’m a fruit
I’m citrus
Multiple Python inheritance are when a class inherits from multiple base classes.
Syntax:
1. class Base1:
2. <class-suite>
3.
4. class Base2:
5. <class-suite>
6. .
7. .
8. .
9. class BaseN:
10. <class-suite>
11.
12. class Derived(Base1, Base2, ...... BaseN):
13. <class-suite>
Syntax
1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>
Eg:
1. >>> class A:
2. x=1
3. >>> class B(A):
4. pass
5. >>> class C(B):
6. pass
7. >>> cobj=C()
8. >>> cobj.x
Output: 1
When more than one class inherits from a class, it is hierarchical Python inheritance.
1. >>> class A:
2. pass
3. >>> class B(A):
4. pass
5. >>> class C(A):
6. pass
7. >>> issubclass(B,A) and issubclass(C,A)
Output: True
1. >>> class A:
2. x=1
3. >>> class B(A):
4. pass
5. >>> class C(A):
6. pass
7. >>> class D(B,C):
8. pass
9. >>> dobj=D()
10. >>> dobj.x
Output: 1
Case 1
This is a simple case where we have class C derived from both A and B. When
method process() is called with object of class C then process() method in class A is
called.
Python constructs the order in which it will look for a method in the hierarchy of
classes. It uses this order, known as MRO, to determine which method it actually
calls.
It is possible to see MRO of a class using mro() method of the class.
Case 2
In this case, we create D from C and B. Classes C and B have process() method and
as expected MRO chooses method from C. Remember it goes from left to right. So it
searches C first and all its super classes of C and then B and all its super classes.
We can observe that in MRO of the output given below.
Case 3
Now, lets change the hierarchy. We create B and C from A and then D from B and C.
Method process() is present in both A and C.
There are some functions in Python which are compatible to run with multiple data
types.
One such function is the len() function. It can run with many data types in Python.
Let's look at some example use cases of the function.
Example 2: Polymorphic len() function
print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))
o/p:
9
3
2
We can then later generalize calling these methods by disregarding the object we
are working with. Let's look at an example:
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")
def make_sound(self):
print("Meow")
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")
def make_sound(self):
print("Bark")
Output
Meow
I am a cat. My name is Kitty. I am 2.5 years old.
Meow
Bark
I am a dog. My name is Fluffy. I am 4 years old.
Bark
Here, we have created two classes Cat and Dog. They share a similar structure and
have the same method names info() and make_sound().
However, notice that we have not created a common superclass or linked the
classes together in any way. Even then, we can pack these two different objects into
a tuple and iterate through it using a common animal variable. It is possible due to
polymorphism.
A Python program to create a Bank class where deposits and withdrawals can
be handled by using instance methods
code:
class Bank_Account:
def __init__(self):
self.balance=0
print("Hello!!! Welcome to the Deposit & Withdrawal Machine")
def deposit(self):
amount=float(input("Enter amount to be Deposited: "))
self.balance += amount
print("\n Amount Deposited:",amount)
def withdraw(self):
amount = float(input("Enter amount to be Withdrawn: "))
if self.balance>=amount:
self.balance-=amount
print("\n You Withdrew:", amount)
else:
print("\n Insufficient balance ")
def display(self):
print("\n Net Available Balance=",self.balance)
s = Bank_Account()
choice=0
while choice<=3:
print(“1:Deposit\n2:Withdraw\n3:Exit”)
choice=int(input(“Enter a choice”)
if choice==1:
s.deposit()
s.display()
elif choice==2:
s.withdraw()
s.display()
elif choice==3:
break
Output:
Conclusion:
Thus we have studied and implemented interitance and its different
types,Constructor overridding and method overridding,Polymorphism and its type
and Method Resolution Order (MRO).