簡體   English   中英

Python調用與命名參數同名的函數

[英]Python calling a function with the same name as named argument

在一個模塊中,我有兩個函數,我們稱它們為fg g采用命名參數f 我想從g內部調用f 如何訪問函數f 不幸的是,由於兼容性問題,我無法更改其名稱。

編輯

為了澄清,這就是我的意思:

def f():
  ... code ...

def g(f=1):
  ... code ...
  x = f() # error, f doesn't name the function anymore
  ... code ...

您可以為函數添加一個新名稱。

例如:

def f():
    pass

f_alt = f

def g(f=3):
    f_alt()

只是不要從模塊中導出f_alt。

使用globals基本示例:

def f():
    print 'f'

def g(name):
    globals()[name]()

g('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')

輸出:

hello
foo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM