Whenever object-oriented programming is done in Python, we mostly come across the __init__ method. This article explains the main concept of __init__ method in Python when used for Windows app development of graphical user interfaces (GUIs).
“__init__” is a reserved method in python classes. It is known as a constructor in object-oriented concepts. This method is called when an object is created from the class and it allows the class to initialize the attributes of a class.
The __init__ method is similar to constructors in C++ and Java. Constructors are used to initialize the object’s state. The task of constructors is to initialize (assign values) to the data members of the class when an object of a class is created. Like methods, a constructor also contains a collection of statements (i.e. instructions) that are executed at the time of Object creation. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.
Here is the basic example of how we can use __init__:
The output in PyScripter IDE:
In the above example, a person named Jim is created. While creating a person, “Jim” is passed as an argument, and this argument will be passed to the __init__ method to initialize the object. The keyword self represents the instance of a class and binds the attributes with the given arguments. Similarly, many objects of the Person class can be created by passing different names as arguments. Here is the example:
The output in PyScripter IDE:
The following code is the working example of using __init__ method in the context of creating GUI using DelphiVCL library:
And here is the GUI result:
Check out Python4Delphi which easily allows you to build Python GUIs for Windows using Delphi.