How to acces variables, from a functions that are inside a class, from the kivy file?

Viewed 214

I know that we can access variables declared in the main class of the app. This can be done using "app.NameOfTheVariable", for example, access to a string value:

#Python file
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout

class MainScreen(MDBoxLayout):
    pass

class MainApp(MDApp):
    App_Name = "Galasken Proyect 001"

MainApp.run()



#Kivy file
MainScreen:
<MainScreen>:
    MDLabel:
       text: app.App_name
  

However, I want to know how can we access variables that are inside a function which is inside a class. For example, in the next code, how can I access to "Object_name"

#Python file
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout

class MainScreen(MDBoxLayout):
    pass

class MainApp(MDApp):
    App_Name = "App Example"

    def a_function(self):
        Object_name = "this is a name"

MainApp.run()

I have tried different things on the kivy file but nothing have workd. These are the things that I have tried:

#Kivy file
MainScreen:
<MainScreen>:
    MDLabel:
       text: app.a_function().App_name
     # text: app.a_function.App_name
     # text: app.App_name   

What can I do to access that variable?

1 Answers

The variable Object_name in the function a_function is inaccessible to you because it is "local" in the scope of the function.

One thing you can do is:

def a_function(self):
    self.Object_name = "this is a name"

This will place Object_name in the scope of MainApp and can be accessed by app.Object_name

NB: This could be side-effect-y. The Object_name member variable in MainApp does not exist until you call a_function(). If you try to access app.Object_name before calling that function, you'll get an error about the Attribute not existing.

You can stop this side effect by adding self.Object_name in your __init__ constructor method. Alternatively, you can just have a_function() return that string directly.

def a_function(self):
    Object_name = "this is a name"
    return Object_name
Related