can a python function call a global function with the same name?(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) 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函数可以调用同名的全局函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python函数可以调用同名的全局函数吗?
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
