简体   繁体   English

python中跨多个文件的全局变量

[英]Global variables across multiple files in python

I have a modules.py file : 我有一个modules.py文件:

global dns_server_ip
def SetVnetGlobalParameters():
    dns_server_ip = '192.168.3.120'

And I'm importing this file in say abc.py file 我在abc.py文件中导入此文件

from modules import *
SetVnetGlobalParameters()
print(dns_server_ip)

But 'dns_server_ip' is still not accessible. 但'dns_server_ip'仍无法访问。

I want to set global parameters through Function only. 我想通过Function设置全局参数。 Any help would be greatly appreciated! 任何帮助将不胜感激! Thanks.. 谢谢..

As per your question I understand you are the beginner to the python. 根据你的问题,我知道你是python的初学者。

While importing the modules you have use just module name and don't need to include the extension or suffix(py) and in your code you miss the starting single quote . 导入模块时,您只使用模块名称,不需要包含扩展名或后缀(py),并且在您的代码中,您会错过起始单引号。

Here is your modified code: it is modules.py 这是您修改过的代码:它是modules.py

dns_server_ip = ''
def SetVnetGlobalParameters():
    global dns_server_ip
    dns_server_ip = '192.168.3.120′

Here is your abc.py 这是你的abc.py

import modules 
modules.SetVnetGlobalParameters()
print modules.dns_server_ip

Here through the global keyword we are telling the python interpreter to change or point out the global variable instead of local variable and always the variable would be either global or local If the variable is both (local and global) you will get python UnboundLocalError exception and if you did not put that global keyword 这里通过全球的关键字,我们告诉Python解释器来改变或指出的全局变量而不是局部变量,始终变量是,要么globallocal如果变量既(本地和全球),你会得到蟒蛇UnboundLocalError例外,如果您没有放置该全局关键字

global dns_server_ip

The dns_server_ip will be created as a new local variable . dns_server_ip将创建为新的局部变量。 The keyword global intended to with in the functions only 关键字global仅用于函数中

you can check global keyword , python modules 你可以检查全局关键字python模块

In modules.py 在modules.py中

dns_server_ip = None
def SetVnetGlobalParameters():
    global dns_server_ip
    dns_server_ip = '192.168.3.120'

In abc.py 在abc.py

import modules
modules.SetVnetGlobalParameters()
print(modules.dns_server_ip)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM