开发者

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

开发者 https://www.devze.com 2023-04-06 15:14 出处:网络
How c开发者_如何学Pythonan I take one variable from one function and use it in another function without having to make that variable global?You have basically two choices.

How c开发者_如何学Pythonan I take one variable from one function and use it in another function without having to make 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 (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.)


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, 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号