In this post we’ll see how to pass object of the class as parameter in Python.
Passing object as parameter
In the example there are two classes Person and MyClass, object of class Person is passed as parameter to the method of class MyClass.
In MyClass there is one method my_method which takes one more argument apart from self.
class MyClass():
def my_method(self, obj):
print('In my_method method of MyClass')
print("Name:", obj.name)
print("Age:", obj.age)
In class Person, MyClass is also used so that is imported.
from MyClass import MyClass
class Person:
def __init__(self, name, age):
print('init called')
self.name = name
self.age = age
def display(self):
print('in display')
print("Name-", self.name)
print("Age-", self.age)
# object of class MyClass
obj = MyClass()
# passing person object to
# method of MyClass (self = person here)
obj.my_method(self)
person = Person('John', 40)
person.display()
In method display() object of MyClass is created.
from MyClass import MyClass
Then the my_method() method of class MyClass is called and object of Person class is passed as parameter.
obj = MyClass()
On executing this Python program you get output as following.
# passing person object to
# method of MyClass (self = person here)
obj.my_method(self)
init called
in display
Name- John
Age- 40
In my_method method of MyClass
Name: John
Age: 40
That's all for this topic Passing Object of The Class as Parameter in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like -