【问题标题】:access variables across different classes using kivy使用 kivy 跨不同类访问变量
【发布时间】:2019-12-05 01:37:07
【问题描述】:

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

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

【问题讨论】:

  • 请发送minimal reproducible example,包括完整的错误信息。
  • 您似乎忘记了 Ans1-3 之前的 self.,但随后 Check1-3 未定义。

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


【解决方案1】:

您在示例中使用了类变量。这里没有错,但请注意,如果您有这些类的多个实例,则每个实例共享类变量。如果一个人更改了一个值,则该值对所有人都进行了更改。

如果该行为不是您想要的,您可能想要使用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

【讨论】:

    猜你喜欢
    • 2019-09-22
    • 1970-01-01
    • 2012-07-05
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多