Home > Blockchain >  how to change the class variable depending on the variable from the constructor?
how to change the class variable depending on the variable from the constructor?

Time:02-17

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

CodePudding user response:

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'

CodePudding user response:

There are two issues:

  • The if..else block executes before any instance is created, so it could not possibly reflect a change to is_check

  • When writing to a class attribute, you should not use self.is_check as 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)
  • Related