1

I would like to understand below behavior of class in python:

class A:
   print("I am in class")

After running this code, without creating any instances I can see that print statement is executed. Without creating an instance, why is this statement executed?

a_jelly_fish
  • 478
  • 6
  • 21
Rahul
  • 49
  • 6

1 Answers1

2

This happens because Python executes all the code in the class body.

If you want print("I am in class") to run only when you create an instance, try defining your class this way and see how the behaviour changes:

class A:
     def __init__(self):
         print("I am in class A")

Just to add on, I believe the answers to this previous question can give you more details: Why does a class' body get executed at definition time?

Desmond Cheong
  • 798
  • 6
  • 19