[英]Python calling a function with the same name as named argument
In a module, I have two functions, let's call them f
and g
. 在一个模块中,我有两个函数,我们称它们为f
和g
。 g
takes a named argument f
. g
采用命名参数f
。 I'd like to call f
from inside g
. 我想从g
内部调用f
。 How do I access the function f
? 如何访问函数f
? Unfortunately, due to compatibility issues, I can't change their names. 不幸的是,由于兼容性问题,我无法更改其名称。
Edit 编辑
To clarify, this is what I mean: 为了澄清,这就是我的意思:
def f():
... code ...
def g(f=1):
... code ...
x = f() # error, f doesn't name the function anymore
... code ...
You could add a new name for the function. 您可以为函数添加一个新名称。
Eg: 例如:
def f():
pass
f_alt = f
def g(f=3):
f_alt()
Just don't export f_alt from the module. 只是不要从模块中导出f_alt。
Basic example using globals
: 使用globals
基本示例:
def f():
print 'f'
def g(name):
globals()[name]()
g('f')
Though globals()
seems like a simple solution here, you can also achieve the same thing by defining a inner function inside g()
that calls the global f
: 尽管在这里globals()
似乎是一个简单的解决方案,但是您也可以通过在g()
内部定义一个调用全局f
的内部函数来实现相同的目的:
def f():print "hello"
def g(f):
def call_global_f():
global f
f()
call_global_f() #calls the global f
print f #prints the local f
g('foo')
output: 输出:
hello
foo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.