問題描述
我可以從同名函數(shù)調(diào)用全局函數(shù)嗎?
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}
我的意思是全局排序函數(shù).有沒有辦法做到這一點?然后我想用模塊名稱調(diào)用我的函數(shù):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)
我想使用相同的名稱,因為它與全局函數(shù)做同樣的事情,只是它添加了一個默認參數(shù).
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
規(guī)則,這意味著當您在函數(shù)中使用非限定名稱時,Python 最多搜索四個范圍——首先本地 (L) 范圍,然后是任何封閉 (E) def
和 lambda
的本地范圍s,然后是全局 (G) 范圍,最后是內(nèi)置 (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)
因此,當您在函數(shù)解釋器中使用 sorted
時,會將其視為 全局 名稱(您的函數(shù)名稱),因此您將擁有一個遞歸函數(shù).如果你想訪問內(nèi)置的 sorted
你需要為 Python 指定它.通過 __builtin__
模塊(在 Python-2.x 中)和 builtins
在 Python-3.x 中(此模塊提供對 Python 的所有內(nèi)置"標識符的直接訪問)
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())
這篇關(guān)于python函數(shù)可以調(diào)用同名的全局函數(shù)嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!