什么时候在Python中初始化类变量?
问题描述:
考虑以下Python 3代码:
Consider the following Python 3 code:
class A:
b = LongRunningFunctionWithSideEffects()
何时会调用 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?
答
此刻该模块已导入
test.py
:
def x():
print('x')
class A:
x = x()
然后
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