在python中通过ref / by ptr发送?

这个问题在这里已经有了答案:

  • 如何通过引用传递变量? 23个答案

  • 在某些方面,Python中的所有调用都是通过引用调用的。 事实上,从某种意义上说,所有变量都是引用。 但是有些类型,比如你的例子中的int ,不能改变。

    例如,在list ,您要查找的功能很简单:

    def change_it(some_list):
        some_list.append("world")
    
    foo = ["hello"]
    change_it(foo)
    print(foo)  # prints ['hello', 'world']
    

    但请注意,重新分配参数变量some_list不会更改调用上下文中的值。

    但是,如果你问这个问题,你可能会想用一个函数来设置两个或三个变量。 在这种情况下,你正在寻找这样的东西:

    def foo_bar(x, y, z):
        return 2*x, 3*y, 4*z
    
    x = 3
    y = 4
    z = 5
    x, y, z = foo_bar(x, y, z)
    print(y)  # prints 12
    

    当然,你可以用Python做任何事情,但这并不意味着你应该做。 以电视节目Mythbusters的风格,这里有一些你想要的东西

    import inspect
    
    def foo(bar):
        frame = inspect.currentframe()
        outer = inspect.getouterframes(frame)[1][0]
        outer.f_locals[bar] = 2 * outer.f_locals[bar]
    
    a = 15
    foo("a")
    print(a) # prints 30
    

    甚至更糟糕:

    import inspect
    import re
    
    def foo(bar):
        # get the current call stack
        my_stack = inspect.stack()
        # get the outer frame object off of the stack
        outer = my_stack[1][0]
        # get the calling line of code; see the inspect module documentation
        #   only works if the call is not split across multiple lines of code
        calling_line = my_stack[1][4][0]
        # get this function's name
        my_name = my_stack[0][3]
        # do a regular expression search for the function call in traditional form
        #   and extract the name of the first parameter
        m = re.search(my_name + "s*(s*(w+)s*)", calling_line)
        if m:
            # finally, set the variable in the outer context
            outer.f_locals[m.group(1)] = 2 * outer.f_locals[m.group(1)]
        else:
            raise TypeError("Non-traditional function call.  Why don't you just"
                            " give up on pass-by-reference already?")
    
    # now this works like you would expect
    a = 15
    foo(a)
    print(a)
    
    # but then this doesn't work:
    baz = foo_bar
    baz(a)  #  raises TypeError
    
    # and this *really*, disastrously doesn't work
    a, b = 15, 20
    foo_bar, baz = str, foo_bar
    baz(b) and foo_bar(a)
    print(a, b)  # prints 30, 20
    

    请,请, 不要这样做。 我只是把它放在这里来激发读者去研究Python中一些比较晦涩的部分。


    据我所知,这在Python中不存在(尽管如果您将可变对象传递给函数,也会发生类似的情况)。 你也可以做

    def test():
        global x
        x = 3
    
    test()
    

    要么

    def test(x):
        return 3
    
    x = test(x)
    

    其中第二个更受欢迎。

    链接地址: http://www.djcxy.com/p/20841.html

    上一篇: Send by ref/by ptr in python?

    下一篇: how to assign variable by reference in python?