OOPs in Python

Components of a class
1.    Data members
2.    Constructor
a.     __init__()
3.    Setter to update the value
4.    Getter to return the value
5.    General methods

Example
Create a class Customer having data members as cid, name and balance.
Create a constructor to initialize data in the data members.
Create required setter and getter
Create a method deposit() to deposit some amount
Create a method withdraw() to withdraw some amount
Solution 1: Fixed data
class Customer:
    def __init__(self,cid,name,opamount):
        self.cid=cid
        self.name=name
        self.balance=opamount
    def setName(self,name):
        self.name=name
    def getCid(self):
        return self.cid
    def getName(self):
        return self.name
    def getBalance(self):
        return self.balance
    def deposit(self,amount):
        self.balance=self.balance+amount
    def withdraw(self,amount):
        self.balance=self.balance-amount

c=Customer(134,"Rakesh Kumar",5000)
c.deposit(6000)
c.withdraw(2000)
print("Balance of",c.getName(),"is",c.getBalance())




Solution 2: User data
class Customer:
    def __init__(self,cid,name,opamount):
        self.cid=cid
        self.name=name
        self.balance=opamount
    def setName(self,name):
        self.name=name
    def getCid(self):
        return self.cid
    def getName(self):
        return self.name
    def getBalance(self):
        return self.balance
    def deposit(self,amount):
        self.balance=self.balance+amount
    def withdraw(self,amount):
        self.balance=self.balance-amount

cid=int(input('Customer ID'))
name=input('Customer Name')
balance=float(input('Opening Amount'))
c=Customer(cid,name,balance)
amount=float(input('Add amount'))
c.deposit(amount)
amount=float(input('Withdarw amount'))
c.withdraw(amount)

print("Balance of",c.getName(),"is",c.getBalance())

Comments

Popular posts from this blog

Converting Excel File to JSON File using xlrd module

Using Oracle with Python

Using time module