首页 > 解决方案 > 什么时候在 Python 中初始化一个类变量?

问题描述

考虑以下 Python 3 代码:

class A:
    b = LongRunningFunctionWithSideEffects()

什么时候会LongRunningFunctionWithSideEffects()调用?目前模块已导入?或者目前该类首次以某种方式使用?

标签: pythonclassstaticinitialization

解决方案


目前模块已导入

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

推荐阅读