Home > Back-end >  Getting list from a function within a different class to a function within a different class
Getting list from a function within a different class to a function within a different class

Time:08-17

I'm playing around with Kivy a bit and can't understand why MenuScreen.number_list doesn't return the list from the MenuScreen class.

class MenuScreen(Screen):
    def process(self):
        self.text = self.ids.input.text
        print(self.text)
    pass

    def submit(self):
        number_list = []
        for i in self.text:
            number_list.append(int(i))

class GuessScreen(Screen):
    def guess(self, number):
        for i in MenuScreen.number_list:
            if correct == True:
                if number == i:
                    print("Correct, next number")
                    correct = True
                else:
                    print("Wrong")
                    correct = False
    pass

CodePudding user response:

EDIT: I realize I misinterpreted the question, number list must be a class variable for it to be called. Leaving this up and it could still be (potentially) useful.

Your code is not returning any values. It stands, this method:

def submit(self):
        number_list = []
        for i in self.text:
            number_list.append(int(i))

appends everything to the list, and then leaves the method. You do not have the 'return' keyword.

def submit(self):
        number_list = []
        for i in self.text:
            number_list.append(int(i))
        return number_list  # <-- this is necessary in ANY function where you wish
                            #     to get some value/object out of the 
                            #     function into a different scope.

This returns the number list from the function after it is called, so you can do something like this:

ms = MainScreen()
my_number_list = ms.submit() 

As a side note, the 'pass' keyword used in your code is not necessary and could cause some unintended behaviors, so I would be aware of this!

CodePudding user response:

You need to declare number_list as a class property so you can use it, otherwise it's just a variable with its scope only inside the method.

class MenuScreen(Screen):
    number_list = []
    def process(self):
        self.text = self.ids.input.text
        print(self.text)
    pass

    def submit(self):
        number_list = []
        for i in self.text:
            number_list.append(int(i))

class GuessScreen(Screen):
    def guess(self, number):
        MenuScreen = MenuScreen(Screen)
        MenuScreen.submit()
        for i in MenuScreen.number_list:
            if correct == True:
                if number == i:
                    print("Correct, next number")
                    correct = True
                else:
                    print("Wrong")
                    correct = False
    pass

And also make sure you create an object for the class and call its methods

  • Related