Python替代全局variab

2024-03-29 14:48:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python项目,其中有一个函数test_function。在test函数中我有一个变量a,但我想在另一个名为test_function2的函数中使用它。我不想使a成为全局变量。还有别的办法吗?你知道吗

def test_function():
    a = "hello"


def test_function2():
    if a == "hello":
        print(a)
    else:
        print("hello world")

Tags: 项目函数testhelloworldifdeffunction
2条回答

Python return statement

The return statement is used to return from a function i.e. break out of the function. We can optionally return a value from the function as well.

def test_function():
    a = "hello"
    return a # returns variable a


def test_function2():
    a = test_function()
    if a == "hello":
        print(a)
    else:
        print("hello world")

test_function2()

你可以这样做。以函数作为参数,并以a作为参数调用它。现在您可以传递任何需要作为输入的函数,而无需在test_function外部公开a。你知道吗

def test_function(func = lambda a : None):
    a = "hello"
    func(a)


def test_function2(a):
    if a == "hello":
        print(a)
    else:
        print("hello world")

test_function(test_function2)

相关问题 更多 >