Python: because when declaring the constructor of the Daughter I also have to declare the constructor of the Mother?

Asked

Viewed 62 times

1

I am developing a small application in Python and I came across a question that I could not draw a concrete conclusion about why this should happen. Simply put, the problem is this::

The following code works normally:

  from kivy.app import App
  from kivy.uix.widget import Widget

  class MyKeyboardListener(Widget):    
      pass     

  class Aplicativo(App):  
      def build(self):  
          return MyKeyboardListener()

  if __name__ == '__main__':  
      Aplicativo().run()  

The problem actually appears when I create the class constructor method, in which case the application no longer works

  from kivy.app import App  
  from kivy.uix.widget import Widget

  class MyKeyboardListener(Widget)
      def __init__(self): <-- após incluir este o problema acontece
            pass

  class Aplicativo(App):  
      def build(self):  
          return MyKeyboardListener()  
  if __name__ == '__main__':  
      Aplicativo().run()

The application only works again when I call the mother constructor method, in this case "Widget"

from kivy.app import App 
from kivy.uix.widget import Widget

class MyKeyboardListener(Widget)
    def __init__(self):
        super.__init__(): <-- Construtor da Mãe

class Aplicativo(App):  
    def build(self):  
        return MyKeyboardListener()

if __name__ == '__main__':  
    Aplicativo().run()

The question in question is why does the program stop working when I declare the constructor (even empty) of the Mykeyboardlistener class? and why the same works again when I call the super class builder?

  • the mother class constructor must initiate variables or flame some method that arrow some parameter within the object, vc declaring the class constructor of the daughter class goes on to write the inherited, so ñ works without the super call()

  • And why don’t you think you should or shouldn’t need to declare?

  • vc only declares if you want to put extra functions, in the case of example script nothing is added or changed, so code is useless

1 answer

0


In the first case you automatically load and overwrite the attributes of your class with the Widget inheritance.

In the second case it doesn’t work because you carry __init__ of its class and overrides the __init__ of the class you inherited.

To solve this, the builder is required super().__init__() within the __init__ of its class created to inherit the attributes of the inherited class.

For example, you create a class with the method __init__:

def __init__(self):
    pass

It is the same that you avoid calling the methods and attributes initializers of the widget that is composed this way:

    def __init__(self, **kwargs):
        # Before doing anything, ensure the windows exist.
        EventLoop.ensure_window()

        # Assign the default context of the widget creation.
        if not hasattr(self, '_context'):
            self._context = get_current_context()

        no_builder = '__no_builder' in kwargs
        self._disabled_value = False
        if no_builder:
            del kwargs['__no_builder']
        on_args = {k: v for k, v in kwargs.items() if k[:3] == 'on_'}
        for key in on_args:
            del kwargs[key]

        self._disabled_count = 0

        super(Widget, self).__init__(**kwargs)

        # Create the default canvas if it does not exist.
        if self.canvas is None:
            self.canvas = Canvas(opacity=self.opacity)

        # Apply all the styles.
        if not no_builder:
            rule_children = []
            self.apply_class_lang_rules(
                ignored_consts=self._kwargs_applied_init,
                rule_children=rule_children)

            for widget in rule_children:
                widget.dispatch('on_kv_post', self)
            self.dispatch('on_kv_post', self)

        # Bind all the events.
        if on_args:
            self.bind(**on_args)

That’s why it’s right to call __init__ with super().__init__.

Reference: https://kivy.org/doc/stable/_modules/kivy/uix/widget.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.