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?

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.

commented: Thanks for the help +2

That makes sense Gribouillis, thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.