什么时候在Python中初始化类变量?

Ser*_*tch 4 python static initialization class

考虑以下Python 3代码:

class A:
    b = LongRunningFunctionWithSideEffects()
Run Code Online (Sandbox Code Playgroud)

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

use*_*740 7

class遇到语句时,类中的代码运行- 即。在导入过程中。

这是因为,与 Java 或 C# 类定义不同,Pythonclass语句实际上是可执行代码。

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

print("Wait for me!")
Run Code Online (Sandbox Code Playgroud)

结果整齐地按执行顺序排列:

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

print("Wait for me!")
Run Code Online (Sandbox Code Playgroud)


Paw*_*ski 6

目前,模块已导入

test.py

def x():
    print('x')

class A:
    x = x()
Run Code Online (Sandbox Code Playgroud)

然后

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
Run Code Online (Sandbox Code Playgroud)