-2

I have seen that if I write this code:

class Test:

   print("inside class")

   def __init__(self):
       pass

Test()

I have this output: 'inside class' It is strange, is a class only a function in python? It is possible to simulate a class with a function?

asv
  • 3,332
  • 7
  • 24
  • 47

1 Answers1

4

No, one point in which they differ is the time when their bodies are executed.

Function and method bodies are not executed on import time, but class bodies (even nested class bodies) are.

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
timgeb
  • 76,762
  • 20
  • 123
  • 145