问题描述
我对Python非常陌生。还没有学过类。使用Python 3.2.2。试过实施一些程序化的C逻辑。我的代码分为两个文件,如下所示。
这个文件叫做date.py
如果(d> = 1且d< = 31),则
是有限日期(d,m,y):
,dd,mm,yy = 0,0,0
def isValidDate并且m≥1且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
这个文件叫做module1.py
$ b 当 module1.py (它是date.dd = 22 )执行时, date.py 中的全局变量值变为 22 并保持这种方式。
但是,当我调用 isValidDate()函数时,即使测试条件已通过,分配也不会似乎是永久的。 isValidDate()函数中的本地打印语句显示为dd分配了值,但是在 main()函数调用 printDate()显示原始值。
发生了什么事?
解决方案全局变量在你的代码中必须标记为这样,否则代码将被赋值给一个局部变量,名称相同(实际上会映射全局变量)。
如中所述:
因此,要解决问题,您需要如下所示:
def isValidDate(d,m,y):
if(d> = 1且d = 1且m global dd ,mm,yy
dd,mm,yy = d,m,y
...
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) #problemthis 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?
解决方案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:
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 ...
这篇关于Python中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!