首页 > 解决方案 > 用构造函数(__init__)中的值填充的全局值未反映在其他python模块中

问题描述

I am trying import global variables defined in one script to other script.

主文件

# import ipdb;ipdb.set_trace()
import sample
expr = ['age < 10', "country == 'China'"]
values = {}
class Test:
    def __init__(self, name, age, country) :
        self.name = name
        self.age = age
        self.country = country
        global values
        values['name'] = name
        values['age'] = age
        values['country'] = country

if __name__ == "__main__" :
    name = raw_input("Enter your name:")
    age = int(input("Enter your age:"))
    country = raw_input("Enter your country:")
    user = Test(name, age, country)
    sample.printValExp()   

示例.py

import main

def printValExp():
    print(main.expr)
    print(main.values)
    # print(main.Test.name)

输出/输出:

[root@dev01 dynamic]# python main.py
Enter your name:sunny
Enter your age:14
Enter your country:japan
['age < 10', "country == 'China'"]
{}
[root@dev01 dynamic]#

在 main.py 中,我定义了 2 个全局变量

--> expr, initialized with list
--> values, as empty dict

未初始化的值字典,我在构造函数中填充了用户输入的详细信息(__ init __

虽然这个dict 填充在 main.py 的 init 方法中,但当我在其他脚本sample.py中导入这个全局变量时,它在那里显示为空

但是当试图打印expr时,这也是在main.py中声明自己时初始化的全局变量,这是打印 expr 值(字符串列表)

我应该怎么做才能在其他脚本中获取全局变量值,其值填充在

__ init __
or inside 
if __ name __ == '__ main __' :

标签: pythonglobal-variablespython-import

解决方案


我不知道为什么上面的内容不起作用,

完全欢迎任何解释

但是我找到了解决给定问题的解决方案,无法扩展全局变量的范围,其值仍然显示为 NULL,尽管它的值填充在 __ init __ ()

我创建了另一个文件 values.py 并实现了外部变量的概念,就像在 C 中一样我按照这个在 python 中设计外部变量的概念,变量值将在不同的文件中共享

值.py

userDict = {}

主文件

import sample
import values


expr = ['age < 10', "country == 'China'"]

class Test:
    def __init__(self, name, age, country) :
        self.name = name
        self.age = age
        self.country = country
        values.userDict['name'] = name
        values.userDict['age'] = age
        values.userDict['country'] = country

if __name__ == "__main__" :
    name = raw_input("Enter your name:")
    age = int(input("Enter your age:"))
    country = raw_input("Enter your country:")
    user = Test(name, age, country)
    sample.printValExp()   

示例.py

import main
import values

def printValExp():
    print(main.expr)
    print(values.userDict)
    # print(main.Test.name)

输出/输出:

[root@dev01 dynamic]# python main.py
Enter your name:sunny
Enter your age:15
Enter your country:japan
['age < 10', "country == 'China'"]
{'country': 'japan', 'age': 15, 'name': 'sunny'}

推荐阅读