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

时间:2013-10-16 16:45:35

标签: python python-3.x

我需要帮助 - 我尝试通过ref / by ptr向c ++中的方法发送值 我怎么能这样做?

以exmple:

 def test(x):
    x=3    

 x=2
 test(x)
 print(x)

在这种情况下,x是测试方法中的局部变量,不会更改“原始”X. 那我怎么能改变“原创”X? 感谢

2 个答案:

答案 0 :(得分:4)

在某些方面,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部分。

答案 1 :(得分:1)

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

def test():
    global x
    x = 3

test()

def test(x):
    return 3

x = test(x)

其中第二个是首选。