initializing an attribute in __init__
-
creating a subclass of Qt class which has custom attributes.
Python complains when an attribute isn't constructed in
__init__
and is constructed in another method, you get something like this:
AttributeError: 'Window' object has no attribute '_Window__menubar'
so what i do is:
# in __init__() self.__menubar = self.menuBar() self.__create_menubar() # in __create_menubar() menu = self.__menubar.addMenu('menu') ...
this code doesn't feel "comfortable" because i init the menu bar (or a widget), then add properties to it in another method.
is this the only way?
-
Hi,
What about using
self.__menubar = None
in the constructor ?With what version of python do you get that message ?
-
@user4592357
PyCharm --- the IDE I use for Python/PyQt --- marksself.
variables which are not created in__init__()
with a harmless "warning underline". But it doesn't really matter. There is no "error message from Python". -
@user4592357
If you wish to ensure you always create theself.
variables in__init__()
, but that's before you are ready to actually create the objects --- e.g. you only create some member widget when the user performs some action --- then as @SGaist said doself.member = None
in__init__()
. That's effectively what happens for C++ code when member variables are declared (which of course you can't do in Python). -
Just a small correction, in C++, class members are not initialised by default, you have to explicitly set their value either in the constructor, constructor initialisation list or since C++11, you can do that at the same place as the declaration.
-
No it's not.
See this excellent article from Arne Mertz on the subject.