在不传递参数的情况下在函数中使用变量 [英] Use a Variable in a Function Without Passing as an Argument

查看:121
本文介绍了在不传递参数的情况下在函数中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,有什么方法可以让函数使用变量并返回它而不将其作为参数传递?

In python is there any way at all to get a function to use a variable and return it without passing it in as an argument?

推荐答案

您提出的要求是可能的.如果某个函数没有重新绑定(例如,分配给它)一个名称,而是使用了该名称,则该名称将被视为一个 global ,例如:

What you ask is possible. If a function doesn't re-bind (e.g, assign to) a name, but uses it, that name is taken as a global one, e.g:

def f():
    print(foo)

foo = 23
f()

将按照您的要求进行操作.但是,这已经是一个可疑的想法:为什么不只是def f(foo):并调用f(23),那么更直接,更清晰?!

will do what you ask. However, it's a dubious idea already: why not just def f(foo): and call f(23), so much more direct and clearer?!

如果函数需要绑定名称,那么即使global语句允许使用该名称,它也会变得更加可疑...:

If the function needs to bind the name, it's even more dubious, even though the global statement allows it...:

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

foo = 23
f()
print(foo)

在这里,好得多的替代方案是:

Here, the much better alternative would be:

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

foo = f(23)
print(foo)

效果相同-更清洁,可维护性更好的结构.

Same effect - much cleaner, better-maintainable, preferable structure.

为什么,当一种更好的方法更容易,更清洁时,您正在寻找劣等(虽然可行)的方法??!

Why are you looking for the inferior (though feasible) approach, when a better one is easier and cleaner...?!

这篇关于在不传递参数的情况下在函数中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆