什么时候在Python中初始化类变量? [英] When is a class variable initialized in Python?

查看:164
本文介绍了什么时候在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

这篇关于什么时候在Python中初始化类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆