How to define global function in Python?

后端 未结 3 664
说谎
说谎 2020-12-10 01:47

Is there a way to define a function to be global from within a class( or from within another function, as matter of fact)? Something similar to defining a global variable.

3条回答
  •  遥遥无期
    2020-12-10 02:27

    You can use global to declare a global function from within a class. The problem with doing that is you can not use it with a class scope so might as well declare it outside the class.

    class X:
      global d
      def d():
        print 'I might be defined in a class, but I\'m global'
    
    >> X.d
    
       Traceback (most recent call last):
       File "", line 1, in 
       AttributeError: 'X' object has no attribute 'd'
    
    >> d()
    
    I might be defined in a class, but I'm global
    

提交回复
热议问题