Python: Why does class variable get assigned?

200 Views Asked by At

Here is my code:

class MyClass:

    def __init__(self):
        self.value = 0

    def set_value(self, value):
        self.value = 5

    def get_value(self):
        return self.value

    value = print("Hello")

a = MyClass()

The output is:

Hello

What I do not understand is why print("Hello") gets executed. When I create an instance of the class only the instance variable is set to 0. Why self.value = 0 calls value = print("Hello")?

Can someone explain me this behavior?

4

There are 4 best solutions below

0
On BEST ANSWER

The code evaluates the class when you execute it, and calls the print to define the class variable value.

The below example shows that it's printed before the instanciation.

class MyClass:

    def __init__(self):
        self.value = 0

    def set_value(self, value):
        self.value = 5

    def get_value(self):
        return self.value

    value = print("Hello")

print('hi')
a = MyClass()

#output
>>> Hello
>>>hi
0
On

It doesn't. That print is executed because it's at the class level itself; the body of a class is executed at the time the class is defined. You would get that output even if you never instantiated MyClass.

0
On

It does not, drop a = MyClass() and it will print "Hello" anyway. It executes code in the body when a class is defined:

class MyClass:
    print(2 * 2)

# prints 4
0
On

Don't let the indentation trick you. value is not an instance variable. value is a class variable because it is defined in the class's scope. It's the same as doing:

class MyClass:
    value = print("Hello")
    ....

Which means that the call to print will run at class definition time. In other words, when Python defines MyClass it also defines all of the class level variables - including value. To define value, it then calls print, which is why Hello is printed before you create an instance of MyClass.

If you want only instances of MyClass to print Hello, put the variable definition inside of the class constructor.

Side note: The print function returns None, so it's seems a bit strange that your assigning the value to a variable. Perhaps you were looking for something like input instead?