如何在一个函数中将同一变量与另一个函数一起使用,而不将该变量设置为全局变量?

发布于 2024-12-06 04:25:07 字数 48 浏览 0 评论 0原文

如何从一个函数中获取一个变量并在另一个函数中使用它,而不必将该变量设置为全局变量?

How can I take one variable from one function and use it in another function without having to make that variable global?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浅浅 2024-12-13 04:25:07

你基本上有两个选择。

一种是将其作为参数传递给第二个函数。 (如果您希望第一个函数看到值的更改,它需要是引用类型(例如字典/列表),并且您必须不覆盖该对象,只能修改它(例如 a.append(b ) 而不是 a = a + [b])。

第二个是定义一个可以用作单例的类,从技术上讲,这仍然是“全局”定义的。它可以让你将事物分组:(

class FooSingleton(object):
    class_var = "foo"

def func1():
    FooSingleton.class_var = "bar"

def func2():
    print(FooSingleton.class_var)

你也可以使用 dict 而不是类来执行此操作;这取决于偏好。)

You have basically two choices.

One is to pass it to the second function as a parameter. (If you want the first function to see changes to the value, it needs to be a reference type (e.g. a dict/list) and you have to not overwrite the object, only modify it (e.g. a.append(b) rather than a = a + [b]).

The second is to define a class that can be used as a singleton. Technically, this is still defining something 'globally', but it lets you keep things grouped:

class FooSingleton(object):
    class_var = "foo"

def func1():
    FooSingleton.class_var = "bar"

def func2():
    print(FooSingleton.class_var)

(You could also do this with a dict instead of a class; matter of preference.)

早茶月光 2024-12-13 04:25:07

让函数接受一个参数,并将该参数传入。

def one_function():
  one_variable = ''
  return one_variable

def another_function(a_param):
  # do something to a_param
  return

have the function take a parameter, and pass that parameter in.

def one_function():
  one_variable = ''
  return one_variable

def another_function(a_param):
  # do something to a_param
  return
随心而道 2024-12-13 04:25:07

技术上可行并且可以使用,例如用于记忆(但它通常隐藏在装饰器后面,并且只有那些确信自己做了正确的事情的人才能实现,即使他们可能仍然对此感到有点不好):

def g():
    if not hasattr(g, "x"):
        g.x = 0
    return g.x

g()
# 0

g.x = 100
g()
# 100

Technically possible and may be used, e.g. for memoisation (but then it is usually hidden behind a decorator and only implemented by people who are sure they do the right thing even though they might still feel a bit bad about it):

def g():
    if not hasattr(g, "x"):
        g.x = 0
    return g.x

g()
# 0

g.x = 100
g()
# 100
老子叫无熙 2024-12-13 04:25:07

您可以使用闭包来处理此问题,或者更自然的是将两个函数定义为类的方法,并将“全局”变量定义为类的成员。

You can use closure to handle this, or more natural is to define both functions as methods of a class and the "global" variable as member of the class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文