Willi Mentzel Willi Mentzel - 1 year ago 48
Python Question

How to pass the reference from inside one object to the constructor of another

Let's say I am inside an object (object1) and I want to pass its reference to another object (object2) I created inside it.

Inside object1:

# ...
self.object2Reference = object2(self)
# ...

Code of object2:

class object2:
def __init__(self, object1Reference)
self.object1Reference = object1Reference
# ...

It fails with the following error:

self.object2 = object2()
TypeError: __init__() takes exactly 2 arguments (1 given)

I want to be able to access variables and methods of object1 from inside object2.

self.object2Reference = object2(self)
happens inside a method that is started via new thread, so self was not what I expected at this time. I tried to make this example as small and simple as possible but forgot one imported aspect doing so. My bad. But the answer is good and complete anyways and also shows the use of inheritance.

Answer Source

To pass the current object to another object it declares for use.

The code:

class Object2:
    def __init__(self, object1):
        self.object1 = object1

class Object1:
    def __init__(self):
        self.object2 = Object2(self)

    def print_something(self):
        print("I am an object1")

x = Object1()

Seems to be what you are trying to do. This works for me, and prints out "I am an object1". If you structure your code like above with your two objects it should work as you hope.


If you are hoping to do inheritance instead of just use the object

I also wanted to add, that if you are looking for inheritance instead of just being able to access object1, you can do that like this:

class Object1:
    def print_something(self):
        print("I am an object1 method inherited by object 2")

class Object2(Object1):
    def __init__(self):

x = Object2()

With this, Object2 will inherit any Object1 methods it does not implement. super().__init__() and putting (Object1) in the class declaration are the only two changes you make here, to then be able to use any Object1 method from self.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download