2

Could you please help me to find the problem? Python code that works:

class ParamWindow:
    def __init__(self, b):
        self.a = b
        print self.a

params = ParamWindow(8)
print params.a

this prints 8 and 8. Ok. Then I do:

class ParamWindow:
    def __init__(self, parent, b):
        self = wx.Frame(parent = parent, id=-1, title="Parameters")
        self.a = b
        print self.a

params = ParamWindow(None, 8)
print params.a

and it says "ParamWindow instance has no attribute 'a'". Why has not it? I told him that self is Frame and then added a field "a" (no error at this point) but when i ask to print it (error at print line), it forgets that "a" exists... Where am I wrong? Thanks.

1 Answer 1

6
def __init__(self, parent, b):
    self = wx.Frame(parent = parent, id=-1, title="Parameters")

Here you reassign self, so you end up having no reference to the ParamWindow instance any more! You should never do that! What are you trying to achieve?

    self.a = b

Here, you assign a to self, which is now the Frame, not the ParamWindow. ParamWindow.a never gets defined and you get the error later on.

Maybe you want to inherit from Frame? If so, your code should look like this:

class ParamWindow(wx.Frame):
    def __init__(self, parent, b):
        # Initialize the superclass (wx.Frame).
        super(ParamWindow, self).__init__(parent=parent, id=-1, title="Parameters")
        self.a = b
        print self.a
Sign up to request clarification or add additional context in comments.

7 Comments

+1. Never assign something to self unless you really know what you are doing.
yeah, but the error is returned at the moment of addressing to "a" but not at the assignment. Is it normal? Why does not it say smth bad on the assignment line? And in total: how should I write to obtain a Frame with an additional field "a" ? Thank you.
@AndrewLazarev because self now has nothing to do with the original instance. You can assign anything you like to it, but it won't affect the instance.
@Ferdinand Beyer, oook, I C! Thanks a lot. Could you please just tell me: if "super" in a key word, why does not my eclipse highlight it? :)
It's not a keyword. It's just a built in function.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.