Aliquis Aliquis - 2 months ago 12
Python Question

Python: Why does instance variable call class variable?

Here my example 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")
is executed. When I create an instance of the class
MyClass
only the instance variable
value
is set to 0. But I don't get why
self.value = 0
apparently also calls
value = print("Hello")
.

Can someone explain me this behaviour?

Answer Source

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