In this chapter, we will discuss how to pass members of one class to another class in Python. Let us now find out how we can do that.
How to pass members of one class to another class?
You can pass members of one class to another class in Python, as shown in the program below.
#this class contains student details
class Student:
#constructor method
def __init__(self,rollno,fullname,marks):
self.rollno = rollno
self.fullname = fullname
self.marks = marks
#instance method
def displayoutput(self):
print("Roll no of student is: ",self.rollno)
print("Full name of student: ",self.fullname)
print("Marks of student: ",self.marks)
#this class displays student details
class Sample:
#method to receive Student class instance
#and show output details
@staticmethod
def mymethod(s):
#increase marks of students by 100
s.marks+=100
s.displayoutput()
#create Student class instance s
s = Student(7, "Raju", 750.75)
#call static method of Sample and pass s
Sample.mymethod(s)
Output
Roll no of student is: 7
Full name of student: Raju
Marks of student: 850.75
In the above program, we have a class Student with a constructor that defines attributes such as rollno, fullname, and marks. It also has an instance method displayoutput() to show the values present in these attributes.
We then created an instance called ‘s‘ for the Student class that contains a copy of all the methods and attributes. We then passed this instance to the method of another class called Sample as ‘Sample.mymethod(s)‘. The mymethod() method in the Sample class has the logic to increase the student’s marks by 100 and then call the displayoutput method of the instance.
You can use this concept to make your programming life enjoyable if you are involved in any Python project. Passing the instance of one class as a parameter to a method of another class will be very helpful in real-world scenarios.