Skip to content
Related Articles

Related Articles

Improve Article
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




# python program to understand the 
# accessing of objects within objects
  
# define class first
class first:
    
    # constructor
    def __init__(self):
        # class second object
        # is created
        self.fst = second()
          
    def first_method(self):
        print("Inside first method")
  
# define class second
class second:
    
    # constructor
    def __init__(self):
        self.snd = "GFG"
          
    def second_method(self):
        print("Inside second method")
  
# make object of first class
obj1 = first()
print(obj1)
  
# make object of second class
# with the help of first
obj2 = obj1.fst
print(obj2)
  
# access attributes and methods 
# of second class
print(obj2.snd)
  
obj2.second_method()
  
# This code is contributed
# by Deepanshu Rustagi.

Output:

<__main__.first object at 0x7fde6c57b828>
<__main__.second object at 0x7fde6c57b898>
GFG  
Inside second method

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :