更改 Python 函数内的基本(不可变)类型?

发布于 2024-07-14 13:50:21 字数 558 浏览 11 评论 0原文

我正在使用 C++ SDK,其中有一个类似的函数(它有一个 python 包装器,但没有文档):

getPos ( int uvId, float & u, float & v ) const 

How do Ispecify in Python so that the Passed Variables were Changed?

我尝试了这个例子,看看是否可以修改函数内部的浮点数,但它不起作用,所以打印了 12.0:

def change ( a ) :

    a = 35.0


b = 12.0

change ( b )

print b

那么我如何调用这个函数,我可以在Python中更改2个外部浮点数?

相关:

I am using a C++ SDK where there is a function like (it has a python wrapper, but not docs):

getPos ( int uvId, float & u, float & v ) const 

How do I specify in Python so that the passed variables are changed?

I tried this example to see if I could modify floats inside a function, but it didn't work, so printed 12.0:

def change ( a ) :

    a = 35.0


b = 12.0

change ( b )

print b

So how do I call this function that I can change 2 external floats in Python?

Related:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

掩耳倾听 2024-07-21 13:50:21

在Python中:

def getPos(uvID):
    # compute u, v
    return u, v

# 
u, v = getPos(uvID)

In Python:

def getPos(uvID):
    # compute u, v
    return u, v

# 
u, v = getPos(uvID)
绝不放开 2024-07-21 13:50:21

据我所知,Python 不支持按引用调用,因此您建议的确切代码不起作用(显然)。

为 C++ 函数生成 Python 包装器的工具(或人)必须做了一些特殊的事情来支持此函数(希望如此,否则您将无法使用它)。 你知道用什么工具来生成包装器吗?

通常这样的工具会生成某种容器数据类型:

b.value = 12.0
change(b)
print b.value

As far I know, Python doesn't support call-by-reference, so the exact code you are suggesting doesn't work (obviously).

The tool (or person) that generated the Python wrapper for the C++ function must have done something special to support this function (hopefully, or you won't be able to use it). Do you know what tool was used to generate the wrapper?

Usually tools like this will generate some sort of container data type:

b.value = 12.0
change(b)
print b.value
莫相离 2024-07-21 13:50:21

对于简单的情况,让函数返回新值。

对于更复杂的情况,您可以传入一个对象或列表并进行更改:

def foobar(alist):
    alist[0] = 10

blist = [42]
foobar(blist)
print blist[0]

编辑:

对于包装 C++ 引用,没有任何标准方法(基本 python 接口位于 C 级别 - 不是 C++) - 所以这取决于python 接口已实现 - 它可能是数组,或返回多个值。 我不确定 boost.python 如何处理它,但您可以从那里开始,或者可以在调试器下查看如何处理参数。

For simple cases have the function return the new value.

For more complicated cases you can pass in a object or a list and have that changed:

def foobar(alist):
    alist[0] = 10

blist = [42]
foobar(blist)
print blist[0]

Edit:

For wrapping C++ references there isn't any standard way (basic python interfaces are at the C level - not C++) - so it depends how the python interface has been implemented - it might be arrays, or returning multiple values. I'm not sure how boost.python handles it but you might start there, or maybe look under a debugger to see how the parameter are handled.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文