I'm writing a Python program with a GUI built with the Tkinter module. I'm using a class to define the GUI because it makes it easier to pass commands to buttons and makes the whole thing a bit easier to understand.
The actual initialization of my GUI takes about 150 lines of code. To make this easier to understand, I've written the __init__
function like so:
def __init__(self, root):
self.root = root
self._init_menu()
self._init_connectbar()
self._init_usertree()
self._init_remotetree()
self._init_bottom()
where _init_menu()
, _init_connectbar()
, and so on do all the initialization work. This makes my code easier to follow and prevents __init__
from getting too big.
However, this creates scope issues. Since an Entry widget that I defined in _init_connectbar()
is in the function scope and is not a class attribute, I can't refer to it in other methods in the class.
I can make these problems go away by doing most of the initialization in __init__
, but I'll lose the abstraction I got with my first method.
Should I expand __init__
, or find another way to bring the widgets into class scope?
The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.
"__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.
The __init__ method of a class is used to initialize new objects, not create them. As such, it should not return any value. Returning None is correct in the sense that no runtime error will occur, but it suggests that the returned value is meaningful, which it is not.
So sometimes you need an __init__() and sometimes you don't If you want to assign instance variables as soon as an instance is created, you need an __init__(). You never need an __init__() to initialize class variables.
Either store some of those widget references in instance variables or return them (a minimal set mind you; you want to Reduce Coupling) and store them in local variables in __init__
before passing the relevant ones as arguments to your subsequent construction helpers. The latter is cleaner, but requires that things be decoupled enough that you can create an ordering that makes it possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With