如何在 class 中定义 class 中的变量并在 IF 语句中使用它

How to define variable in class out of class and use it in IF statement

大家好。学了2个月Python,现在正在学OOP。我有一个问题:

class Test():
x = 0

def __init__(self):

    if Test.x == 5:
        print("OK")
    else:
        print("ERROR")
        
i = Test()
i.x = 5

这是输出:

ERROR

如果 x = 5,为什么这段代码 return 给我一个“错误”?在我看来,它可能 return 我一个“好的”

当您将 Test class x 初始化为 0 时,您会得到 ERROR 输出 你想做的可能是这样的

class Test():
    def __init__(self, value):
        if value == 5:
            print("OK")
        else:
             print("ERROR")

i = Test(5) 打印 OK