Moritz Moritz - 1 year ago 216
Python Question

kivy screens. Do I have to initialize with super?

From the docs:

# Declare both screens
class MenuScreen(Screen):

class SettingsScreen(Screen):

From this SO question:

class WelcomeScreen(Screen):
def __init__(self, **kwargs):

Under which circumstances is it necessary to initialize the screen with
and why ?

Answer Source

Short answer:

No you don't have to use super when defining a Screen. Yes you do always have to __init__ with super (if you use __init__).

Longer answer:

It's nothing unique to screens. In the docs example, you aren't calling __init__ and passing any parameters so no super is necessary. You don't need an __init__ call to define a Kivy Screen. From the SO question, if you're running __init__ you're passing **kwargs up the object hierarchy and also re-defining __init__ which would normally run the initialization of the parent class. super is used to allow you to pass **kwargs and run the parent __init__ without an explicit call to the parent class, in this case, Screen inherits from RelativeLayout, which itself inherits from FloatLayout; without a super call you're overriding the parent class.

You don't need to call __init__ unless you have some use for it. Here is a Screen from one of my apps, with no __init__ call (layout is set in the .kv file):

class LoginScreen(Screen):
    def login(self):
        self.parent.current = 'ParameterScreen'

You will use __init__ if you want to set the layout, content, properties, etc. of a screen at the moment when you instantiate the class you have created without defining these things in the .kv file; to do that you will also need super as described above. It's good practice in kivy though to use the .kv file when you can.

In this example, I want to be able to access BottomBar's parent with self.caller, which I pass in as a **kwargs when I create it, and have this be defined as soon as the bar is instantiated; so I need to define it in __init__ which requires a super call.

class BottomBar(ActionBar):
    titletext = StringProperty('')
    def __init__(self,**kwargs):
        self.caller = kwargs.get('caller')
    def change_title(self,newtitle):
        self.titletext = newtitle
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download