Search code examples
pythonpython-3.xkivynumber-formatting

print the value of a NumericProperty() kivy


If I have a Numeric Property in two of my screens that count how many times a person clicked the correct icon and I want to print it in a separate class how would I do this? I have tried using the print() function and using print(StringProperty(str())) but I dont get a number value printed. When I print the correct_counter in VerifyAA() and VerifyBB() the correct value is printed.

class A(Screen):
    correct_counter1 = NumericProperty(0)
    def verifyAA(self, *args):
        if self.AA == V.Check1 or self.AA == V.Check2 or self.AA == V.Check3:
            print("You got it!!!")
            self.correct_counter1 =  self.correct_counter1 + 1
            print(self.correct_counter1)
            self.ids.aa.disabled = True

class B(Screen):
    correct_counter2 = NumericProperty(0)
    def verifyBB(self, *args):
        if self.BB == VV.Check1 or self.BB == VV.Check2 or self.BB == VV.Check3:
            print("You got it!!!")
            self.correct_counter2 =  self.correct_counter2 + 1
            print(self.correct_counter2)
            self.ids.bb.disabled = True

class Answers(Screen):
    print(A.correct_counter1)
    print(StringProperty(str(B.correct_counter2)))

This is what gets printed respectively:

<NumericProperty name=correct_counter>
<StringProperty name=>

Solution

  • You need to understand the distinction between the definition of a class and an instance of a class. When you print A.correct_counter1 you print the NumericProperty object itself, defined at class level. That's the only sensible result - it wouldn't make sense for it to print the value of the property, because it doesn't have a value. For instance, if you wrote instance1 = A(correct_counter1=1); instance2 = A(correct_counter1=20) what value would you have expected print(A.correct_counter1) to print? The answer has to be neither, the value of the property is defined in each case for the class instance, not the class itself.

    The correct solution is that you must print the value of the property via an instance of your class. For instance, if you write instance = A(); print(instance.correct_counter1) you will print a number like you expect. The best way to do this depends on the structure of your program and the relationship between the classes. Your example isn't a runnable program so it isn't possible to make a specific suggestion. If you have an actual example where you want to do this but can't work out how, post that as a new question.