I want to change the class variable depending on the variable from the constructor.
In the case of the code below, I expect the console to show Yes but the result is No.
How could I change the variable by the constructor?
here is the code:
class MyClass:
is_check = False
def __init__(self, is_check):
self.is_check = is_check
if is_check:
val = 'Yes'
else:
val = 'No'
print(MyClass(True).val)
Python 3.8
>Solution :
The class definition should look like this –
There is an indentation issue as pointed out by @trincot
The variable var should be a object variable, as in make it self.var
The variable declaration has to be className.variable for it to not create an instance variable , and have only one variable for all objects of the class to use as in class variable. Pointed out by @juanpa.arrivillaga
class MyClass:
is_check = False
def __init__(self, is_check):
MyClass.is_check = is_check
if is_check:
self.val = 'Yes'
else:
self.val = 'No'