Monday, June 19, 2023

Passing Object of The Class as Parameter in Python

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 self as one of the argument and another argument is obj, that is where I intend to pass an object of Person class.
 
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 MyClass
In 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

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

  1. Class And Object in Python
  2. Constructor in Python - __init__() function
  3. Multiple Inheritance in Python
  4. Method Overloading in Python
  5. Abstract Class in Python

You may also like-

  1. Accessing Characters in Python String
  2. Python Conditional Statement - if, elif, else Statements
  3. Python Program to Display Armstrong Numbers
  4. JVM Run-Time Data Areas - Java Memory Allocation
  5. Linear Search (Sequential Search) Java Program
  6. Passing Arguments to getBean() Method in Spring
  7. Connection Pooling With Apache DBCP Spring Example
  8. Word Count MapReduce Program in Hadoop

No comments:

Post a Comment