-1

I am not able to understand this code and the concept behind such output. I am creating two objects but only one "Hello" is printed in console. I have tried to figure out through "id" but both the ids are different from each other:

class lol:
    print("Hello")        # Output: Hello
                          # 16377072 16378920
h = lol()
k = lol()
print(id(h), id(k))
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Sai
  • 1
  • 2
  • 3
    `hello` is printed when you define the class, not when you create the objects. – Barmar Aug 24 '21 at 15:21
  • 1
    If you want something to be done when you create a class instance, put it in the class's `__init__()` method. – Barmar Aug 24 '21 at 15:21
  • 1
    The class body is executed when *defining* the class, not instantiating it. Why would you assume the ``print`` to run twice? – MisterMiyagi Aug 24 '21 at 15:21
  • Does this answer your question? [Python method after create an object](https://stackoverflow.com/q/48722512/6045800) – Tomerikoo Aug 24 '21 at 15:24

2 Answers2

1

"Hello" prints only once: As is mentioned in a comment, since lol is a class, the print statement is only executed when the class definition is evaluated.

ids are distinct: You are checking the unique id for the two objects h and k. Since these are distinct objects, their identifiers are unique.

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
1

Anything in the class definition that's not inside a method function is executed once, at the time the class is defined.

When you create an instance of the class, its __init__() method is executed (if you define one). That's where you should put per-instance actions.

class lol:
    print("defining class")

    def __init__(self):
        print("creating instance")

h = lol()
k = lol()
print(id(h), id(k))

This should print:

defining class
creating instance
creating instance
16377072 16378920

(The numbers at the end will obviously be different.)

Barmar
  • 741,623
  • 53
  • 500
  • 612