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

Time:11-07

Everyone hello. I have learning Python for 2 months, and now I am learning OOP. And I have a question:

class Test():
x = 0

def __init__(self):

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

And this is output:

ERROR

Why this code returns me an "ERROR", if x = 5? In my opinion it may return me an "OK"

CodePudding user response:

When you initialize your Test class x in 0 so you get the ERROR output what you want to do is probably something like this

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

i = Test(5) prints OK

  • Related