Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a class variable initialized in Python?

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?

like image 879
Serge Rogatch Avatar asked Dec 31 '18 19:12

Serge Rogatch


People also ask

How are variables initialized in Python?

Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

How do you declare a class variable in Python?

Create Class VariablesA class variable is declared inside of class, but outside of any instance method or __init__() method. By convention, typically it is placed right below the class header and before the constructor method and other methods.

Are class variables initialized?

In C++, class variables are initialized in the same order as they appear in the class declaration.

What does it mean to initialize a class in Python?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.


1 Answers

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
like image 162
Paweł Kordowski Avatar answered Oct 07 '22 04:10

Paweł Kordowski