python函数可以调用同名的全局函数吗?
问题描述
我可以从同名函数调用全局函数吗?
Can I call a global function from a function that has the same name?
例如:
def sorted(services):
return {sorted}(services, key=lambda s: s.sortkey())
{sorted}
我的意思是全局排序函数.有没有办法做到这一点?然后我想用模块名称调用我的函数:service.sorted(services)
By {sorted}
I mean the global sorted function.
Is there a way to do this?
I then want to call my function with the module name: service.sorted(services)
我想使用相同的名称,因为它与全局函数做同样的事情,只是它添加了一个默认参数.
I want to use the same name, because it does the same thing as the global function, except that it adds a default argument.
解决方案
Python 的名称解析方案有时被称为 LEGB
规则,这意味着当您在函数中使用非限定名称时,Python 最多搜索四个范围——首先本地 (L) 范围,然后是任何封闭 (E) def
和 lambda
的本地范围s,然后是全局 (G) 范围,最后是内置 (B) 范围.(请注意,一旦找到匹配项,它将立即停止搜索)
Python's name-resolution scheme which sometimes is referred to as LEGB
rule, implies that when you use an unqualified name inside a function, Python searches up to four scopes— First the local (L) scope, then the local scopes of any enclosing (E) def
s and lambda
s, then the global (G) scope, and finally the built-in (B) scope. (Note that it will stops the search as soon as it finds a match)
因此,当您在函数解释器中使用 sorted
时,会将其视为 全局 名称(您的函数名称),因此您将拥有一个递归函数.如果你想访问内置的 sorted
你需要为 Python 指定它.通过 __builtin__
模块(在 Python-2.x 中)和 builtins
在 Python-3.x 中(此模块提供对 Python 的所有内置"标识符的直接访问)
So when you use sorted
inside the functions interpreter considers it as a Global name (your function name) so you will have a recursion function. if you want to access to built-in sorted
you need to specify that for Python . by __builtin__
module (in Python-2.x ) and builtins
in Python-3.x (This module provides direct access to all ‘built-in’ identifiers of Python)
蟒蛇2:
import __builtin__
def sorted(services):
return __builtin__.sorted(services, key=lambda s: s.sortkey())
蟒蛇3:
import builtins
def sorted(services):
return builtins.sorted(services, key=lambda s: s.sortkey())
相关文章