Access object within another objects in Python
Last Updated :
20 Aug, 2020
Prerequisite: Basics of OOPs in Python
In this article, we will learn how to access object methods and attributes within other objects in Python. If we have two different classes and one of these defined another class on calling the constructor. Then, the method and attributes of another class can be accessed by first class objects ( i.e; objects within objects ).
Here in the below example we learn to access object (its methods and attributes) within an object. We define two classes (class first and class second) with proper definitions.
- First class consists of a constructor and a method.
- The constructor form an object of the second class in the attribute of the first class.
- The method defines the presence in first class method.
- Similarly, the second class consists of a constructor and a method.
- The constructor form an attribute.
- The method defines the presence in the second class method.
As the attribute of first class work as an object of the second class so all the methods and attributes of the second class can be accessed using this:
object_of_first_class.attribute_of_first_class
Below is the implementation:
Python3
class first:
def __init__( self ):
self .fst = second()
def first_method( self ):
print ( "Inside first method" )
class second:
def __init__( self ):
self .snd = "GFG"
def second_method( self ):
print ( "Inside second method" )
obj1 = first()
print (obj1)
obj2 = obj1.fst
print (obj2)
print (obj2.snd)
obj2.second_method()
|
Output:
<__main__.first object at 0x7fde6c57b828>
<__main__.second object at 0x7fde6c57b898>
GFG
Inside second method
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...