模块

时间:2018-03-06 05:31:10

标签: python scope global-variables

以下是我的文件和输出。我想做的就是在xfunc1()获得20的价值import globalVarI have already referred to this answer。我想知道为什么这不起作用?是否有必要使用from globalVar import *代替#globalVar.py x=10

globalVar.py

from globalVar import *

def func1():
    global x
    x=20
    print("X in fun1",x)

fun1.py

from fun1 import *
from globalVar import *

print("X before fun1=",x)
func1()
print("X after fun1=",x)

main.py

X before fun1= 10  
X in fun1 20  
X after fun1= 10

输出:

Rails.application.routes.draw do
  devise_for :admin_users, path: :admin, skip: [:registration], :controllers => {
    :sessions => 'admin_users/sessions'
  }
  namespace :admin do
    root to: "admin_users#index"
    resources :admin_users
  end
end

2 个答案:

答案 0 :(得分:1)

更新答案:

试试这个:

<强> GlobalVar.py:

global x
x = 10

<强> fun1.py:

import GlobalVar

def func1():
    GlobalVar.x = 20
    print("X in fun1", GlobalVar.x)

<强> main.py:

from fun1 import *
from GlobalVar import *

print("X before fun1=", GlobalVar.x)
func1()
print("X after fun1=", GlobalVar.x)

检查这一点,这将根据您的问题为您提供所需的输出。

希望这会对你有所帮助!谢谢! :)

注意:全局表字典是当前模块的字典(在函数内部,这是一个定义它的模块,而不是调用它的模块)

答案 1 :(得分:0)

这不起作用的原因是 main.py中的fun1()方法调用不返回x的更新值,即20。 这就是为什么更新的x的范围仅在执行结束时才在fun1中,值丢失&amp;当你第三次打印x的值时,它只是简单地引用回全局变量

你可以做些什么让它发挥作用 1.fun1.py

from globalVar import *

def func1():
    global x
    x=20
    print("X in fun1",x)
    return x //here it returns the value of 20 to be found later

2.globalVar.py

x=10

3.main.py

from fun1 import *

print("X before fun1=",x)
x = func1()//here the updated value of x is retrived and updated, had you not done this the scope of x=20 would only be within the func1()
print("X after fun1=",x)