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.
class MyClass(): def my_method(self, obj): print('In my_method method of MyClass') print("Name:", obj.name) print("Age:", obj.age)In MyClass there is one method my_method which takes one more argument apart from self.
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 class Person, MyClass is also used so that is imported.
from MyClass import MyClassIn method display() object of MyClass is created.
obj = MyClass()Then the my_method() method of class MyClass is called and object of Person class is passed as parameter.
# passing person object to # method of MyClass (self = person here) obj.my_method(self)On executing this Python program you get output as following.
init called in display Name- John Age- 40 In my_method method of MyClass Name: John Age: 40
Recommendations for learning (Udemy Courses)
- Complete Python Bootcamp Course
- The Complete Python Course-Learn Python by Doing
- Python and Django Full Stack Web Developer Bootcamp
- Python for Data Science and Machine Learning
- Java Programming Masterclass Course
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-
No comments:
Post a Comment