Global Variable in Python

為{幸葍}努か 提交于 2019-12-18 09:09:41

问题


I am very new to Python. Not learnt classes yet. Using Python 3.2.2. Tried implement some procedural C logic. My code is spread over 2 files as follows.

this file is called date.py

dd,mm,yy=0,0,0

def isValidDate(d,m,y):
    if(d>=1 and d<=31 and m>=1 and m<=12):
        dd,mm,yy=d,m,y #problem
        print(dd,mm,yy) #problem
        print(d,m,y) #problem
        return True
    else:
        return False

def printDate():
    print(dd,mm,yy) #problem

this file is called module1.py

import date

def main():
    dd,mm,yy = 23,1,1984
    valid = date.isValidDate(dd,mm,yy) #problem
    print (valid)
    date.printDate()
    date.dd=22 #problem
    date.printDate()

if __name__ == '__main__':
    main()

The lines that I have commented as "problem" are giving me problems.

When the statement in module1.py (which is "date.dd=22") executes, the value of the global variable in date.py changes to 22 and stays that way.

But when I call the isValidDate() function, even though the test condition is passed, the assignment does not seem to be permanent. The local print statement in isValidDate() function shows that "dd" is assigned the value, but in the main() function the call to printDate() shows the original values.

What is going on?


回答1:


To assign values to a global variable in your code you've got to mark it as such, otherwise the code would be assigning to a local variable with the same name (that would be actually shadowing the global variable).

As explained in the documentation:

It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

Hence, to fix the problem, you'd need something like this:

def isValidDate(d,m,y):
    if(d>=1 and d<=31 and m>=1 and m<=12):
        global dd, mm, yy
        dd,mm,yy=d,m,y
        ...



回答2:


Your date.isValidDate function does not operate on the globalvariables dd, mm, yy - it rather operates on (function) local variables with the same names.

In order for date.isValidDate to change the (module) global values of the variables you want, you have to declare them as global at the top of the function - like this:

def isValidDate(d,m,y):
    global dd, mm, yy
    ...


来源:https://stackoverflow.com/questions/8883000/global-variable-in-python

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