20

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?

1
  • 1
    I highly suggest reading throught the Python class documentation. 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. Commented Dec 31, 2018 at 21:01

3 Answers 3

20

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
Sign up to request clarification or add additional context in comments.

Comments

9

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!

1 Comment

I beleive it is the same in Java as well. Static variables initialized at the time of class loader.
4

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.