什么时候在 Python 中初始化静态变量? [英] When are static variables initialized in Python?

查看:79
本文介绍了什么时候在 Python 中初始化静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码

class Foo:
    i = 1 # initialization
    def __init__(self):
        self.i += 1

t = Foo()
print(t.i)

i 的初始化究竟何时发生?init方法执行之前还是在之后执行?

When exactly does the initialization of i take place? Before the execution of the init method or after it?

推荐答案

之前

__init__ 方法在 Foo 实例化之前不会运行.i=1 在代码中遇到类定义时运行

The __init__ method isn't run until Foo is instantiated. i=1 is run whenever the class definition is encountered in the code

您可以通过添加打印语句看到这一点:

You can see this by adding a print statements:

print('Before Foo')
class Foo:
    i = 1
    print(f'Foo.i is now {i}')
    
    def __init__(self):
        print('Inside __init__')
        self.i += 1
        print(f'i is now {self.i}')
print('After Foo')

print('Before __init__')
foo = Foo()
print('After __init__')

打印:

Before Foo
Foo.i is now 1
After Foo
Before __init__
Inside __init__
i is now 2
After __init__


但是请注意,您的 self.i += 1 不会修改类属性 Foo.i.

foo.i # This is 2
Foo.i # This is 1

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

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