Use of “global” keyword in Python

后端 未结 10 2431
既然无缘
既然无缘 2020-11-21 05:05

What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to us

10条回答
  •  旧巷少年郎
    2020-11-21 05:52

    It means that you should not do the following:

    x = 1
    
    def myfunc():
      global x
    
      # formal parameter
      def localfunction(x):
        return x+1
    
      # import statement
      import os.path as x
    
      # for loop control target
      for x in range(10):
        print x
    
      # class definition
      class x(object):
        def __init__(self):
          pass
    
      #function definition
      def x():
        print "I'm bad"
    

提交回复
热议问题