python函数可以调用具有相同名称的全局函数吗? [英] can a python function call a global function with the same name?
问题描述
我可以从具有相同名称的函数中调用全局函数吗?
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 中为)和 Python-3.x中的> builtins
(此模块可直接访问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)
python 2:
import __builtin__
def sorted(services):
return __builtin__.sorted(services, key=lambda s: s.sortkey())
python 3:
import builtins
def sorted(services):
return builtins.sorted(services, key=lambda s: s.sortkey())
这篇关于python函数可以调用具有相同名称的全局函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!