Python Forum

Full Version: How do I reference a method in another class?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How do I reference a method in my BoxLayout class from my App class?

class ConjugationGame(BoxLayout):
    round = 1
    game_state = 0
    def change_game_state(self):
        if self.game_state > 4:
            self.game_state == 1
        else:
            self.game_state += 1


class ConjugationApp(App):
    def build(self):
        Window.bind(on_key_down=self.key_down)
        return ConjugationGame()

    def key_down(self, key, scancode=None, *_):
        if scancode == 281:  # PAGE_DOWN
            print("PAGE_DOWN pressed")
            ConjugationGame.change_game_state()
When I press Page Down, I get this error:

Quote:TypeError: change_game_state() missing 1 required positional argument: 'self'
On line 18, you need to call the method on an instance of the ConjugationGame class. You could of course just add the parens to that line to call ConjugationGame's __init__, but obviously then you'd be creating a new instance on every call of key_down. Is that what you want?
(Feb-29-2020, 08:00 PM)ndc85430 Wrote: [ -> ]On line 18, you need to call the method on an instance of the ConjugationGame class. You could of course just add the parens to that line to call ConjugationGame's __init__, but obviously then you'd be creating a new instance on every call of key_down. Is that what you want?

I don't think that's what I want, but I'm not entirely sure how this all works. Is the App class creating an instance of the BoxLayout class when it returns it in the build method? If so, can I just create a variable in the general namespace and return that variable instead (for the purposes of calling a method on it)?
Solved: I had to pass self.root into ConjugationGame.change_game_state().