0

When I run this code:

class C(object):
    print("Hello from inside class C")

It gives the same result as if I had used this code:

print("Hello from inside class C")

However when I use:

class B(object):
    def __init__(self):
        print("Hello from inside class B")

The class behaves like I had expected. Does anyone have an explanation?

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by HiHe
2

The explanation is that the code in a class body is executed when a module is loaded, like code at module level, while code in a function or method is only executed when the function is called. So in your last example, the print statement is executed when you create a B instance, and not when class B is defined.
Of course, if a class definition is included in a function's body, its code is executed each time the function is called and not when the module is loaded.

Edited by Gribouillis: n/a

Votes + Comments
Thanks for the help
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.