Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 862

Passing Object of The Class as Parameter in Python

$
0
0

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 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. JVM Run-Time Data Areas - Java Memory Allocation
  2. Invoke Method at Runtime Using Java Reflection API
  3. Array in Java
  4. Switch-Case Statement in Java
  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

Viewing all articles
Browse latest Browse all 862

Trending Articles