Python在另一个模块中更改变量并保存它

时间:2017-10-23 20:28:37

标签: python package global-variables global

我有一个名为my_package的简单python包,包含三个文件:

初始化的.py

from .a import func
from .settings import var

settings.py

var = 1

a.py

import .settings

def func():
    settings.var = 2

当我将此包添加到PATH并导入它时,我在脚本下运行,无法得到预期的结果:

import my_package

my_package.func()
print(my_package.var)

我希望得到'2',但它会返回'1'。我在这里做错了什么?

1 个答案:

答案 0 :(得分:-1)

It happens because during import my_package a my_package.var is set to refer to int with value of 1. After running my_package.func() this reference is not touched, however my_package.settings.var is changed to point at new int object with value 2.

import my_package  # imports my_package.var with value 1 

my_package.func()  # sets my_package.settings.var to 2
print(my_package.var)  # prints 1
print(my_package.settings.var)  # prints 2

If you try to do the same with list, you can make it will work differently. By not creating new object at my_package.settings.list_var but rather modifying an entry in existing list.

# __init__.py
from .a import func
from .settings import list_var

_

# settings.py
list_var = [1]

_

# a.py
import .settings

def func():
    settings.list_var[0] = 2

Now running the similar code will actually change the list_var

import my_package  # imports my_package.var with value 1 

print(my_package.var[0])  # prints 1
my_package.func()  # sets list_var to [2]
print(my_package.var[0])  # prints 2