简体   繁体   English

如何在Python中定义全局函数?

[英]How to define global function in Python?

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. 类似于定义全局变量。

Functions are added to the current namespace like any other name would be added. 将函数添加到当前名称空间,就像将添加任何其他名称一样。 That means you can use the global keyword inside a function or method: 这意味着您可以在函数或方法中使用global关键字:

def create_global_function():
    global foo
    def foo(): return 'bar'

The same applies to a class body or method: 同样适用于类主体或方法:

class ClassWithGlobalFunction:
    global spam
    def spam(): return 'eggs'

    def method(self):
        global monty
        def monty(): return 'python'

with the difference that spam will be defined immediately as top-level class bodies are executed on import. 区别在于,将在导入时执行顶级类主体时立即定义spam

Like all uses of global you probably want to rethink the problem and find another way to solve it. 像对global所有使用一样,您可能想重新思考问题并找到另一种解决方法。 You could return the function so created instead, for example. 例如,您可以返回如此创建的函数。

Demo: 演示:

>>> def create_global_function():
...     global foo
...     def foo(): return 'bar'
... 
>>> foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> create_global_function()
>>> foo
<function foo at 0x102a0c7d0>
>>> foo()
'bar'
>>> class ClassWithGlobalFunction:
...     global spam
...     def spam(): return 'eggs'
...     def method(self):
...         global monty
...         def monty(): return 'python'
... 
>>> spam
<function spam at 0x102a0cb18>
>>> spam()
'eggs'
>>> monty
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'monty' is not defined
>>> ClassWithGlobalFunction().method()
>>> monty()
'python'

You can use global to declare a global function from within a class. 您可以使用global从类内部声明全局函数。 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 "<stdin>", line 1, in <module>
   AttributeError: 'X' object has no attribute 'd'

>> d()

I might be defined in a class, but I'm global

I found a case where global does not have the desired effect: inside .pdbrc file. 我发现了一种情况,其中global并没有理想的效果:.pdbrc文件中。 If you define functions in .pdbrc they will only be available from the stack frame from which pdb.set_trace() was called. 如果在.pdbrc中定义函数,则只能从调用pdb.set_trace()的堆栈框架中使用它们。

However, you can add a function globally, so that it will be available in all stack frames, by using an alternative syntax: 但是,您可以全局添加一个函数,以便使用替代语法在所有堆栈框架中都可用:

def cow(): print("I'm a cow")
globals()['cow']=cow

I've tested that it also works in place of the global keyword in at least the simplest case: 我已经测试过,至少在最简单的情况下,它也可以代替global关键字:

def fish():
    def cow(): 
        print("I'm a cow")
    globals()['cow']=cow

Despite being more verbose, I thought it was worth sharing this alternative syntax. 尽管较为冗长,但我认为值得分享这种替代语法。 I have not tested it extensively so I can't comment on its limitations vs using the global keyword. 我没有对其进行广泛的测试,因此无法对它的局限性和使用global关键字进行评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM