16

Consider the following Python 3 code:

class A:
    b = LongRunningFunctionWithSideEffects()

When will LongRunningFunctionWithSideEffects() be called? At the moment the module is imported? Or at the moment the class is first used in some way?

Rinzler786
  • 109
  • 1
  • 11
Serge Rogatch
  • 13,865
  • 7
  • 86
  • 158
  • 1
    I highly suggest reading throught the [Python class documentation](https://docs.python.org/3/tutorial/classes.html). The class-based OOP of Python is similar but different enough from C++ for there to be many areas where things are not working as you think they *should*. – juanpa.arrivillaga Dec 31 '18 at 21:01

3 Answers3

18

At the moment the module is imported

test.py:

def x():
    print('x')

class A:
    x = x()

then

Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
x
Paweł Kordowski
  • 2,688
  • 1
  • 14
  • 21
8

The code inside a class runs when the class statement is encountered - ie. during the import itself.

This is because, unlike in Java or C# class definitions, Python class statements are actually executable code.

class A:
  print("I'm running!") # yup, code outside a method or field assignment!
  b = print("Me too!")

print("Wait for me!")

The result is neatly in order of execution:

I'm running!
Me too!
Wait for me!
user2864740
  • 60,010
  • 15
  • 145
  • 220
2

It is done at the time of import. These are called static variables and are defined at the class level. These variables are created 1 per class and NOT 1 per object. They are part of loading the class which happens at the time of import.

Following is an example:

classA.py

class A:
    print("Printing before Static Variable Creation")
    class_var = 1

    def __init__(self):
        instance_var = 2

main.py

from classA import A

Printing before Static Variable Creation

print('Printing Class Variable Value : ',A.class_var)

Printing Class Variable Value : 1

print(A.__dict__)

{'module': 'classA', 'class_var': 1, 'init': function classA.A.init(self), 'dict': attribute 'dict' of 'A' objects, 'weakref': attribute 'weakref' of 'A' objects, 'doc': None}

solver149
  • 395
  • 3
  • 11