When are static variables initialized in Python?

那年仲夏 提交于 2021-02-05 07:48:45

问题


Consider the following code

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

t = Foo()
print(t.i)

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


回答1:


Before.

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__')

which prints:

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

Notice however, that your self.i += 1 does not modify the class attribute Foo.i.

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



回答2:


The class attribute is initialized the first time you use the ClassName in the source code, also you use the class attribute in the code by doing ClassMethod.attribute

class Foo:
    i = 1 # initialization
    def __init__(self):
        #Use ClassName.attribute to access class attribute
        Foo.i += 1

#I used the Name of the class here, Foo.i will be 1
print(Foo.i)
#1

#Instantiated Foo
t = Foo()

#Value of i changes to 2
print(t.i)
#2


来源:https://stackoverflow.com/questions/55983397/when-are-static-variables-initialized-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!