Header Ads

Objects as Function Parameters using Python | Returning Objects from Member Functions Using Python

Object can Also be passed as Parameters to member Functions. The Method of passing objects to a Functions as Parameters is same as Passing other simple Variables. In this Article we create a program using Python

Program Source Code:

class Travel:
   
def __init__(self):
       
self.km = 0
       
self.hr = 0
   
def getData(self):
       
self.km = int(input("Enter Kilometer Traveled :"))
        
self.hr = int(input("Enter Hours Traveled :"))
   
def display(self):
       
print("You Traveled ",self.km," in ",self.hr," Hours")
   
def add(self,p):
        t = Travel()
        t.km =
self.km + p.km
        t.hr =
self.hr + p.hr
       
print("Total Traveled ",t.km," in ",t.hr)

obj1 = Travel()
print("--------Input Value of Object 1 ---------")
obj1.getData()
print("----------Output Value of Object 1 -------")
obj1.display()
obj2 = Travel()
print("--------Input Value of Object 2 ---------")
obj2.getData()
print("----------Output Value of Object 2 -------")
obj2.display()
print("---Total Kilometer and Hours of obj1 and objct 2---"
)
obj1.add(obj2)
Related Video

Returning Objects from Member Functions Using Python

The method of returning an object from member function is

same as returning a simple variable. if a member function

returns an object its return type is should be the same as

the type of object to be return


Program Source Code:

class travel:
   
def __init__(self):
       
self.km = 0
       
self.hr = 0
   
def getData(self):
      
self.km= int(input("Enter Kilometers Traveled :"))
      
self.hr = int(input("Enter Hours Traveled :"))
   
def show(self):
       
print("You Traveled :",self.km," in ",self.hr," Hours")
   
def add(self,P):
        t = travel()
        t.km =
self.km + P.km
        t.hr =
self.hr + P.hr
       
return t
obj1 = travel()
obj2 = travel()
print("Input Value of Object 1")
obj1.getData()
print("Input Value of Object 1")
obj2.getData()
print("Value of Object 1")
obj1.show()
print("Value of Object 2")
obj2.show()
obj3 = obj2.add(obj1)
print("Value of Object 3 (Total sum of obj1 and objct 2)"
)
obj3.show()
Related Video

No comments

Powered by Blogger.