'how to change the class variable depending on the variable from the constructor?
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 1:[1]
There are two issues:
The
if..elseblock executes before any instance is created, so it could not possibly reflect a change tois_checkWhen writing to a class attribute, you should not use
self.is_checkas assigning to that will create an instance attribute that just happens to have the same name.
For val you could create a property, so that it will always reflect the current value of the class attribute. In this case you can use self.is_check, but only if you don't make the mistake mentioned in the previous point
So:
class MyClass:
is_check = False
def __init__(self, is_check):
MyClass.is_check = is_check
@property
def val(self):
return 'Yes' if self.is_check else 'No'
print(MyClass(True).val)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | trincot |
