Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anything wrong with a really large __init__?

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?

like image 350
Rafe Kettler Avatar asked Sep 19 '10 15:09

Rafe Kettler


People also ask

Is __ init __ important?

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.

What does __ init __ means?

"__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.

Does __ init __ return anything?

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.

Can a class exist without __ Init__ function?

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.


1 Answers

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.

like image 181
Donal Fellows Avatar answered Sep 22 '22 13:09

Donal Fellows