python execjs 网站_Python ExecJS JavaScript引擎使用Python类

我尝试在Python中使用JavaScript引擎。在

我需要在JavaScript中使用Python类,反之亦然——在Python中使用JavaScript代码。我怎么能做到呢?在

在Java中,我有工作代码:package test.test;

import javax.script.Bindings;

import javax.script.Invocable;

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

import javax.script.ScriptException;

import javax.script.SimpleBindings;

public class JavaScriptInJava {

public static void main(String[] args) throws ScriptException, NoSuchMethodException {

ScriptEngineManager manager = new ScriptEngineManager();

ScriptEngine engine = manager.getEngineByName("JavaScript");

/* ----------------------------------------------------------------------- */

// Work with Java class from JavaScript:

String userScript =

"user1.setName(\"Test User\"); "

+ "print( user1.getName() ); ";

Bindings bindings = new SimpleBindings();

User u = new User();

bindings.put("user1", u);

engine.eval(userScript, bindings);

// Work with Java class from JavaScript.

/* ----------------------------------------------------------------------- */

// Use JavaScript function in Java code:

String math =

"function addition(a, b) { "

+ " return a+b; "

+ "} "

+ " "

+ "function substraction(a, b) { "

+ " return a-b; "

+ "} "

+ " ";

engine.eval(math);

Invocable inv = (Invocable) engine;

int a = 10;

int b = 5;

System.out.println("A=" + a + " B=" + b);

Object aPlusB = inv.invokeFunction("addition", a, b);

System.out.println("A+B = " + aPlusB);

Object[] inputParams = {

new Integer(10),

b

};

Object aMinusB = inv.invokeFunction("substraction", inputParams);

System.out.println("A-B = " + aMinusB);

int x = (Integer) aPlusB + 1;

System.out.println("aPlusB + 1 = " + x);

// Use JavaScript function in Java code.

/* ----------------------------------------------------------------------- */

}

}

在用户.java

^{pr2}$

如何将其重写为Python?在import execjs

execjs.runtime = 'Node'

class Clazz:

a = 10

b = 20

c = "test"

def add(self):

return self.a + self.b

x = Clazz()

print x.add()

ctx = execjs.compile("""

function add(x, y) {

return x + y;

}

""")

print ctx.call("add", 1, 2)

在Python中使用JavaScript函数是可以的。但是我不能在JavaScript中使用Python类/变量。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值