Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading