简体   繁体   中英

How do I use the same variable in one function with another function, without making that variable Global?

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

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 (eg a dict/list) and you have to not overwrite the object, only modify it (eg 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.)

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

Technically possible and may be used, eg 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM