Python OOPs Concepts 5

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()               

Output:

Enter pno 1002
Enter product name lux
Enter product rate 36
Enter product quantity 6
pno  1002
name  lux
rate  36.0  Qty  6.0
Cost  216.0
>>> 

Python Method Overloading

Like other languages (for example method overloading in C++) do, python does not support method overloading. We may overload the methods but can only use the latest defined method.

Example:

#function overloading
def add(n1,n2):
    s=n1+n2
    print("sum = ",s)

def add(n1,n2,n3):
    s=n1+n2+n3
    print("sum = ",s)

#function calling
#add(10,20) #error
add(10,20,30)

In the above code we have defined two add method, but we can only use the second add() method, as python does not supports method overloading. We may define many method of same name and different argument but we can only use the latest defined method. Calling the other method will produce an error.
Like here calling add(10,20) will produce an error as the latest defined product method takes three arguments.

Visitor Counter

0051104