Ad

Not Sure What Form.__init__(self) Does?

- 1 answer

I am looking at some code for making a tabbed split image viewer with IronPython using windows forms and there is a line in the init function that I don't understand and cannot see an explanation for when I google it.I have placed a comment next to the line in question.

Below is some code, it is just boiler plate code that will bring up an empty form.

import clr
clr.AddReference('System.Windows.Forms')

from System.Windows.Forms import Application, Form

class MainForm(Form):

    def __init__(self):
        Form.__init__(self) #what is this line doing?
        self.Show()

Application.EnableVisualStyles()
form = MainForm()
Application.Run(form)

Elsewhere on the page http://www.voidspace.org.uk/ironpython/winforms/part11.shtml it has a finished program which kind of works (the tabs do nothing when you add extra images) but still has the same line in the init function, does anyone kow what it does?

Ad

Answer

The class MainForum is an extension of the class Form.

All the Form.__init__(self) does, is calling the constructor of the Form class.

Small Example: Let's make 2 classes Human and Student. A Human has a name and that's all he does. A Student is a Human but has additional attributes like a school he visits. Also he is able to tell you his name.

class Human():
  def __init__(self, name):
    self.name = name #We set the name of the human

class Student(Human):
   def __init__(self, name, school):
     self.school = school
     Human.__init__(self, name) #We set the name of the Human inside of the Person
   def tellName(self):
     print(self.name)

   student1 = Student("John Doe","ETH Zurich")
   student1.tellName()   

Output: John Doe

You can think of it like the Parent class is now a part of the Subclass. A Student is inside still a Human.

Ad
source: stackoverflow.com
Ad