Thursday, March 9, 2017

Inheritance Python

Tags

Inheritance is the process of reusing the existing code .
Define new classes from the old one i.e including all features of old classes.

Following Program will illustrate the concept:

Code::


class bankaccount:
    def __init__ (self):
        self.bal=int(input("Enter Initial Balance:"))
   
    def withdraw(self,amt):
        if amt<self.bal:
            self.bal=self.bal-amt
        else:
            raise ValueError ("Insufficient Funds")
   
    def deposit(self,amt):
        self.bal=self.bal+amt
   
    def transfer(self,amt,toacc):
        try:
            self.withdraw(amt)
            toacc.deposit(amt)
        except ValueError as e:
            print("Try Again",e)
    def __str__(self):
        return"Balance is: "+str(self.bal)

class cheque(bankaccount):
    def __init__ (self):
        bankaccount.__init__(self)
        self.cheq={}
    def process(self,amt,number,org):
        try:
            self.withdraw(amt)
        except ValueError as e:
            print("Cheque Returned for",e)
        self.cheq[number]=(org,amt)
    def cheqinfo(self,number):
        if self.cheq.get(number):
            print(self.cheq[number])
        else:
            print("No Such Cheque")
    def withdraw(self,amt):
        print('Withdrawing')
        bankaccount.withdraw(self, amt)

nt=bankaccount()        #object of bankaccount type created
nt.deposit(1500)
print(nt)
nt.withdraw(1500)
print(nt)
nti=bankaccount()          #new object created
nt.transfer(1500, nti)
print(nt,nti)

dn=cheque()
dn.process(1500, 1001, 'nearur')

dn.cheqinfo(1001)

Output::