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函数可以调用同名的全局函数吗?
基础教程推荐
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
