在函数中使用变量而不作为参数传递

Mat*_*jic 2 python variables arguments function

在 python 中,有没有办法让函数使用变量并返回它而不将其作为参数传递?

Ale*_*lli 5

你问的可能的。如果函数没有重新绑定(例如分配)名称,而是使用它,则该名称将被视为全局名称例如:

def f():
    print(foo)

foo = 23
f()
Run Code Online (Sandbox Code Playgroud)

会按照你的要求做。然而,这已经是一个可疑的想法:为什么不直接使用def f(foo):and call f(23),这样更直接、更清晰?!

如果函数需要绑定名称,那就更可疑了,即使global语句允许......:

def f():
    global foo
    print(foo)
    foo += 1

foo = 23
f()
print(foo)
Run Code Online (Sandbox Code Playgroud)

在这里,更好的选择是:

def f(foo):
    print(foo)
    foo += 1
    return foo

foo = f(23)
print(foo)
Run Code Online (Sandbox Code Playgroud)

相同的效果 - 更干净、更易于维护、结构更好。

当更好的方法更容易、更干净时,为什么你还要寻找较差的(尽管可行)方法......?!