我可以从同名函数调用全局函数吗?
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) defs and lambdas, 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())
这篇关于python函数可以调用同名的全局函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
python:不同包下同名的两个模块和类python: Two modules and classes with the same name under different packages(python:不同包下同名的两个模块和类)
配置 Python 以使用站点包的其他位置Configuring Python to use additional locations for site-packages(配置 Python 以使用站点包的其他位置)
如何在不重复导入顶级名称的情况下构造python包How to structure python packages without repeating top level name for import(如何在不重复导入顶级名称的情况下构造python包)
在 OpenShift 上安装 python 包Install python packages on OpenShift(在 OpenShift 上安装 python 包)
如何刷新 sys.path?How to refresh sys.path?(如何刷新 sys.path?)
分发带有已编译动态共享库的 Python 包Distribute a Python package with a compiled dynamic shared library(分发带有已编译动态共享库的 Python 包)