Aliquis
Aliquis

Reputation: 2309

Python: Why does class variable get assigned?

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?

Upvotes: 0

Views: 194

Answers (4)

PRMoureu
PRMoureu

Reputation: 13327

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

Upvotes: 3

Chris
Chris

Reputation: 22953

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?

Upvotes: 2

Danil Speransky
Danil Speransky

Reputation: 30453

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

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599610

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.

Upvotes: 3

Related Questions