Home > Software design >  How does passing an instance of one class to another work?
How does passing an instance of one class to another work?

Time:01-25

For a couple of days I've been attempting to pass an instance of a variable from one of my classes to another, and until recently I have not been able to get it to work. I've read this document regarding classes and instances, I've searched online and stackoverflow and I couldn't get an answer until I tried a solution from a previous asked question and it solved my problem. However, I'm not exactly sure on the why and the how it works.

My code goes as follows, :

from tkinter import *

def main():
    main_window = Tk()
    app = First(main_window)
    main_window.mainloop()

class First:
    def __init__(self, root):
        self.root = root
        self.root.title('First Window')

        self.entry1 = Entry(self.root)
        self.entry1.pack()

        btn = Button(self.root, text="click", command=self.clicked)
        btn.pack()
    def clicked(self):
        writeDoc(First=self)

class writeDoc:
    def __init__(self, First):
        self.First = First
        txt = self.First.entry1.get()
        print(txt)

if __name__ == '__main__'
    main()

Under the class writeDoc whenever I hover over the parameter First it is not a reference to the Class First, so I am unsure how it has access to entry1. The same goes for the First within writeDoc(First=self). Addtionally, why does writeDoc(First=self) work but not writeDoc(self.First)?

I assumed when I want to reference to another class and want to pass its instances over I would need to do

class First:
....
def clicked(self):
writeDoc(First)
....

class writeDoc(First):
    def __init__(self, First):
    super().__init__(First):
...

But, this didn't work for me at all.

I hope this isn't a loaded/jumbled question. I want to understand how this works to create better code and avoid misunderstanding how python classes works.

CodePudding user response:

Inside the clicked() method, self refers to an instance of the First class. It then does

writeDoc(First=self)

which passes that instance to the writeDoc class's __init__() method, as the value of its First parameter. This is no different from passing any other object as a method parameter.

writeDoc(self.First) doesn't work because there's no First attribute in the self instance. First is the name of the class, not an attribute.

  • Related