Python OOPs Concepts | Classes and Objects

Example:6
Python program to create a class named bank with attributes as accno, name and bal. Take input for the details and display them?
Sol:

class bank:
    accno=0
    name=""
    bal=0
    def input(self):
        self.accno=int(input("Enter accno "))
        self.name=input("Enter name ")
        self.bal=float(input("Enter balance "))
    def show(self):
        print("accno ",self.accno)
        print("Name ",self.name)
        print("Bal ",self.bal)

#calling
#creating an object
b=bank()
#invoking the method of class
b.input()
b.show()

Output:

Enter accno 1002
Enter name Amit
Enter balance 5000
accno 1002
Name Amit
Bal 5000.0

Example:7
Python program to create a class named student with attributes as roll, name, marks of three subject (m1,m2,m3),total and per. Take input for the details and display them?
Sol:

#class creation
class student:
    roll=0
    name=""
    m1=0
    m2=0
    m3=0
    total=0
    per=0
    def input(self):
        self.roll=int(input("Enter roll no "))
        self.name=input("Enter name ")
        self.m1=float(input("Enter m1 "))
        self.m2=float(input("Enter m2 "))
        self.m3=float(input("Enter m3 "))

    def cal(self):
        self.total=self.m1+self.m2+self.m3
        self.per=self.total/3
        
    def show(self):
        print("roll ",self.roll)
        print("name ",self.name)
        print("m1 ",self.m1," m2 ",self.m2," m3 ",self.m3)
        print("total ",self.total," per ",self.per)
        

#object creation
s=student()
s.show()
s1=student()
s1.input()
s1.cal()
s1.show()

Output:

roll 0
name
m1 0 m2 0 m3 0
total 0 per 0
Enter roll no 1001
Enter name Amit
Enter m1 98
Enter m2 97
Enter m3 95
roll 1001
name Amit
m1 98.0 m2 97.0 m3 95.0
total 290.0 per 96.66666666666667

Example:8
Python program to create a class named product with attributes as pno, name, rate, qty and cost. Take input for the details, calculate and display cost of the product?
Sol:

class product:
    pno=0
    name=0
    rate=0
    qty=0
    cost=0
    def input(self):
        self.pno=int(input("Enter pno "))
        self.name=input("Enter product name ")
        self.rate=float(input("Enter product rate "))
        self.qty=float(input("Enter product quantity "))
    def calculate(self):
        self.cost=self.rate * self.qty
    def show(self):
        print("pno ",self.pno)
        print("name ",self.name)
        print("rate ",self.rate," Qty ",self.qty)
        print("Cost ",self.cost)

#creating object
p=product()
p.input()
p.calculate()
p.show()