使用kivy访问不同类别的变量

时间:2019-07-26 17:26:08

标签: python python-3.x function class variables

我正在尝试跨类访问变量以比较字符串。我以为可以使用全局变量,但是只有在为全局变量赋值时才可以使用。我要在一类中从列表中分配每个随机变量字符串,然后在另一类中进行相同的操作,然后进行比较以查看它们是否匹配。

class A(screen):
    check1 = ""
    check2 = ""
    check3 = ""

    def on_enter(self):
        rand_files = ["hello", "goodbye", "what"]
        Check1, Check2, Check3 = rand_files

class B(screen):
    Ans1 = ""
    Ans2 = ""
    Ans3 = "" 
    Ans4 = "" 
    Ans5 = "" 
    Ans6 = ""  

    def on_enter(self):
        rand_files = ["hello", "night", "goodbye", "day", "what", "morning"]
        Ans1, Ans2, Ans3, Ans4, Ans5, Ans6 = rand_files

    def verifyAns1(self):
        if Ans1 == Check1 or Ans2 == Check2 or Ans3 == Check3:
            print("You got it!!!")
        else:
            print("Try again")

当我尝试这样做时,我收到错误消息:

NameError: name 'Ans1' is not defined

1 个答案:

答案 0 :(得分:0)

您在示例中使用类变量。此处没有问题,但是请注意,如果您有这些类的多个实例,则每个实例都共享类变量。如果更改一个值,则所有值都会更改。

如果该行为不是您想要的,则可能要使用Python properties.

并不是说一种方法一定比另一种更好,而是您希望如何控制变量的范围。

话虽如此,这是一个使用类变量可以解决您的问题的示例:

class A:
    a0 = 0
    a1 = 1
    a2 = 2

    def __init__(self):
        print('hello from A')
        print(A.a0)
        print(B.b2)


class B:
    b0 = 3
    b1 = 4
    b2 = 5

    def __init__(self):
        print('hello from B')
        print(A.a2)
        print(B.b0)


A()
B()

结果:

hello from A
0
5
hello from B
2
3