调用weakref传递的Python函数

Pau*_*nta 0 c++ python boost

使用Boost.Python,有没有办法调用已经通过weakref?传递的Python函数?以下代码不起作用:

import weakref

def foo():
    print 'it works'

def func():
    return weakref.ref(foo)
Run Code Online (Sandbox Code Playgroud)

以下是C++:

object module = import("test");
object func(module.attr("func"));
object foo = func();
foo(); // Should print 'it works', but it prints nothing
Run Code Online (Sandbox Code Playgroud)

但是,如果我传递没有weakref的函数对象,它一切正常.有没有办法让这项工作?

mde*_*ous 5

来自weakref文档:

返回对象的弱引用.如果指示对象仍然存在,则可以通过调用引用对象来检索原始对象 ...

所以,给你的片段:

import weakref

def foo():
    print "It Works!"

def func():
    return weakref.ref(foo)

ref = func() # func returns the reference to the foo() function
original_func = ref() # calling the reference returns the referenced object
original_func() # prints "It Works!"
Run Code Online (Sandbox Code Playgroud)