北城已荒凉 2009-01-08 05:45 采纳率: 0%
浏览 346
已采纳

在函数中使用全局变量

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

  • 写回答

17条回答 默认 最新

  • 北城已荒凉 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.

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

报告相同问题?

悬赏问题

  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?