Dialog Chapter Exception in dialogs_2.py and Code from Book

I think I found an error in the book and dialogs_2.py file in the provided examples. In the below provided code, an error is hit on the dlg = CustomDialog(self) line, TypeError: __init__() takes 1 positional argument but 2 were given. I solved it by removing the self reference but would like if someone could explain why that fixes it. Is it because the function already has self in it and this is attempting to pass self to the CustomDialog class’ __init__ twice?

Function that Python complains about below. Changing it to dlg = CustomDialog() resolves it.

def button_clicked(self, s):
        print("click", s)
        dlg = CustomDialog(self)
        if dlg.exec_():
            print("Success!")
        else:
            print("Cancel!")

Hi @byron

Firstly, thanks for the heads up this has been fixed in the latest version of the book (you can download it from the homepage when logged in).

To answer your question — the self here actually refers to the window, and we’re passing it to the CustomDialog object we’re creating, for it to use as a parent.

In the CustomDialog class, e.g.

class CustomDialog:
    
    def __init__(self, parent):
         ...

…the self we pass from button_clicked will actually become parent in the init block. The first parameter of an object method (self by convention) always refers to the object the method is on.

Hope that clears it up for you?