撒拉嘿哟木头 2009-01-08 05:45 采纳率: 100%
浏览 509
已采纳

在函数中使用全局变量

How can I create or use a global variable in a function?

If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?

转载于:https://stackoverflow.com/questions/423379/using-global-variables-in-a-function

  • 写回答

18条回答 默认 最新

  • Memor.の 2009-01-08 08:39
    关注

    You can use a global variable in other functions by declaring it as global in each function that assigns to it:

    globvar = 0
    
    def set_globvar_to_one():
        global globvar    # Needed to modify global copy of globvar
        globvar = 1
    
    def print_globvar():
        print(globvar)     # No need for global declaration to read value of globvar
    
    set_globvar_to_one()
    print_globvar()       # Prints 1
    

    I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global keyword.

    See other answers if you want to share a global variable across modules.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(17条)

报告相同问题?

悬赏问题

  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退