Python - Access a function above outside a class

0

Hello everyone! A question about Python.

I have a structure something like this:

class Tela(FloatLayout):
   def exemplo(self):
      print("teste")

   class botao(Button):
      ?????

Explaining: It is a screen that has a function and a class. I was wondering how do I access the function that is in the "Screen" class within the "button" class. I thought it might be something like: variable = Screen.example () or root.example (), but none of this worked. How is this done?

    
asked by anonymous 13.02.2018 / 14:50

1 answer

1

There is no gain or reason to define classes within classes in Python. (Okay, there's actually a very secondary reason: you may want to use your classes as namespaces to hold values)

But in this case you get nothing. What your "Screen" will need to have are instances of "Booting" the instances you create when you create your "Screen" instance - but I repeat: there is no gain, no benefit, nothing, nothing to define a class within another. On the other hand, by doing this you will work against the language, and several things under the hood that are there to help you begin to work against. Can not, from within the nested class, accessing the class above is just one of those things.

So, what should you do? Keep attributes within your classes that connect them to related objects - for example: a button will need to know which screen it is on - then it should receive this information when it is created.

Look how simple it is:

class Botao:
   def __init__(self, tela):
       self.tela = tela
       ...
   def acao(self):
       self.tela.acao_global()

class Tela:
   def __init__(self):
        self.botao_ok = Botao(self)
        self.botao_cancela = Botao(self)

   def acao_global(self):
       # chamada quando o método "acao" de qualquer botao é executado
    
13.02.2018 / 16:04