是实例化为';无';Python中的传递值?

是实例化为';无';Python中的传递值?,python,python-3.x,Python,Python 3.x,可能重复: 如果我有一个变量并将其实例化为None,我如何进行赋值以反映多个范围中的更改 例如: def doStuff(test): test = "hello world" def main(): test = None doStuff(test) print(test) 如果我猜对了,那么输出什么都不是,因为“test”是通过值传递的?有没有一种方法可以让它通过引用传递,而不用在函数之前静态声明类型?您可以查看全局关键字 def doStuff():

可能重复:

如果我有一个变量并将其实例化为None,我如何进行赋值以反映多个范围中的更改

例如:

def doStuff(test):
    test = "hello world"

def main():
    test = None
    doStuff(test)
    print(test)

如果我猜对了,那么输出什么都不是,因为“test”是通过值传递的?有没有一种方法可以让它通过引用传递,而不用在函数之前静态声明类型?

您可以查看
全局
关键字

def doStuff():
    global test
    test = 'Hello World'
global
关键字允许您直接为全局变量赋值。

执行此操作时:

def main():
    test = None
    doStuff(test)
    print(test)
您必须打印
main()
范围内的字符串对象(由
test
引用引用)。要打印由
doStuff
中的
test
变量引用的内部字符串对象,您应该执行以下三项操作之一:

  • 您应该在
    doStuff

  • 或者使用
    global
    关键字

  • 从存储在
    main()
    test
    中的
    doStuff
    返回一个值


对于最后一部分,您可以找到更多信息。

如果希望
doStuff
更改
main()
范围中
test
的值,您应该返回它,如下所示:

def doStuff(test):
    test = "hello world"
    return test

def main():
    test = None
    test = doStuff(test)
    print(test)
当然,在本例中,没有理由通过测试作为
doStuff()
的输入,所以您可以这样做:

def doStuff():
    test = "hello world" # These 2 lines could be one
    return test          # return "hello world"

def main():
    test = doStuff()
    print(test)

您不能直接从另一个函数更改局部变量的值——正如其他函数所回答的,您可以将其声明为全局变量,或者返回新值并赋值。但另一种尚未提及的实现方法是使用在属性中保存值的包装器类。然后可以传递包装器实例并修改属性:

class Wrapper():
    """a simple wrapper class that holds a single value which defaults to None"""
    def __init__(self, value=None):
        self.value = value

def main():
    test = Wrapper()
    doSomething(test)
    print(test.value)

def doSomething(x):
    x.value = "something"

然后不要使用它,除非你真的必须这样做。只需要做你的函数返回测试