user3124200
user3124200

Reputation: 353

Why is the print statement in the class executed when an object isn't even created?

When I run the code below the output is "hello".

However, the print statement is part of the class pl, and i never created an instance of the class pl, so why is the print statement being executed?

class pl:
    def __init__(self,a,b):
        self.aa=a
        self.bb=b
    print("hello")

Upvotes: 1

Views: 75

Answers (1)

timgeb
timgeb

Reputation: 78690

Class bodies (even nested class bodies) are executed at import time (as opposed to functions or methods).

Demo script:

class Upper:
    print('Upper')
    class Mid:
        print('Mid')
    def method(self):
        class Low:
            print('Low')
        print('method')

Output:

$ python3
>>> import demo
Upper
Mid

Upvotes: 7

Related Questions