假设我在 Python 中有以下类:
class TestPy:
def __init__(self):
pass
def f(self):
return("Hello World")
我想从 Haxe 中调用函数 TestPy.f
。然后我可以通过指定外部类来告诉编译器这个函数
extern class TestPy {
public function new():Void;
public function f():String;
}
然后使用此声明来调用此函数
class Test {
public static function main():Void {
var py:TestPy = new TestPy();
trace(py.f());
}
}
这可以编译,但是生成的代码如下所示:
# Generated by Haxe 3.4.7
# coding: utf-8
class Text:
__slots__ = ()
@staticmethod
def main():
py = TestPy()
print(str(py.f()))
Text.main()
这不起作用,因为带有 TestPy
类的模块永远不会在代码中导入:
NameError: name 'TestPy' is not defined
所以我的问题是如何建议 Haxe 将导入语句(例如 from testmodule import TestPy
)添加到生成的代码中?
最佳答案
只需将 @:pythonImport
元数据添加到您的 extern 中即可。
所以,类似于:
@:pythonImport('testmodule', 'TestPy')
extern class TestPy {...
免责声明:尚未对此进行测试,因此这可能不是完全正确的答案,但元数据是 documented in the manual .
关于python - 从 Haxe 内部调用外部 Python 类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50009486/