python 动态创建函数在RunTime获取自身Name的问题

import sys
from types import FunctionType, MethodType
class aMeta(type):
    def __new__(cls,name,bases,dct):
        attr={
            "__test_func__":FunctionType(cls.testFunc.__code__,cls.testFunc.__globals__,"__test_func__",cls.testFunc.__defaults__,cls.testFunc.__closure__),
            "__test_method__": MethodType(cls.testFunc,cls),
            "__test_dynamic_method__": MethodType(FunctionType(cls.testFunc.__code__,cls.testFunc.__globals__,"__test_func__",cls.testFunc.__defaults__,cls.testFunc.__closure__),cls)
        }
        for k,v in dct.items():
            if k not in attr:
                attr[k]=v
        return super(aMeta,cls).__new__(cls,name,bases,attr)

    def testFunc(self):
        print(sys._getframe().f_code.co_name)

class aTestCls(metaclass=aMeta):
    def __init__(self):
        super().__init__()


if __name__ == "__main__":
    t= aTestCls()
    t.__test_func__()
    t.__test_method__()
    t.__test_dynamic_method__()
    
    print(t.__test_func__.__func__.__name__)
    print(t.__test_method__.__func__.__name__)
    print(t.__test_dynamic_method__.__func__.__name__)

从输出来看:

t.__test_func__()

t.__test_method__()

t.__test_dynamic_method__()

输出为:testFunc

print(t.__test_func__.__func__.__name__)
print(t.__test_method__.__func__.__name__)
print(t.__test_dynamic_method__.__func__.__name__)

分别输出:

__test_func__

test_func

__test_func__

从实际运行结果来看:

FunctionType:是以testFunc为蓝本动态创建了一个函数,但是testFunc的CodeType没有做任何改变,也就是说co_name还是testFunc; 而FunctionType的name参数仅是改变了对象实例的__name__; 这也就造成了t.__test_func(),t.__test_method__,t.__test_dynamic_method__()的调用输出还是testFunc;

MethodType:仅是一个method-wapper;

如果需要动态创建函数,并在函数执行过程中获取函数本身的名称可以考虑以下两个方案:

1、通过定义一个FunctionOverride类,本类实现初始化保存__name__,并重写__call__方法; 在meta里实例化对应对象;

2、通过ast动态生成函数:

        2.1 不通过sys._getframe().f_code.co_name获取方法名:

                在函数本身内部定义一个__name__常量,保存函数本身名称,那么在函数内部可以通过调用__name__获取函数本身名称; 

        2.2 通过sys._getframe().f_code.co_name获取方法名

(以上两种方案本人均已代码验证过可行性;有兴趣的朋友可以自行按方案实现相关代码,在此就不写太多了)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Java中调用Python函数的方法有很多种。一种方法是使用Java调用Python脚本的方式来执行Python代码。这需要使用到Java中的 `Runtime.getRuntime().exec()` 方法。 例如: ``` String pythonScriptPath = "path/to/python/script.py"; String[] cmd = new String[2]; cmd[0] = "python"; // check version of installed python: python -V cmd[1] = pythonScriptPath; // create runtime to execute external command Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(cmd); // retrieve output from python script BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = ""; while((line = bfr.readLine()) != null) { // process each output line form python script System.out.println(line); } ``` 另一种方法是使用第三方库,例如 Jython 或 JPype,来在Java代码中直接调用Python函数。 使用Jython,你可以这样调用Python函数: ``` import org.python.util.PythonInterpreter; PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec("from module_name import function_name"); interpreter.exec("result = function_name(param1, param2)"); PyObject result = interpreter.get("result"); ``` 使用JPype,你可以这样调用Python函数: ``` import JPype; JPype.startJVM(JPype.getDefaultJVMPath()); JPype.importModule("module_name"); function = JPype.JClass("module_name").function_name; result = function(param1, param2); JPype.shutdownJVM(); ``` 请注意,在使用上述方法之前,你需要确保在你的系统中已经安装了Python解释器和所需的Python模块。 ### 回答2: 在Java中调用Python函数通常有以下几种方法: 1. 使用Java的Runtime类来执行Python脚本。可以使用Runtime类的exec方法调用python命令,并在命令中指定要执行的Python脚本文件路径。例如: ```java import java.io.*; public class CallPythonFunc { public static void main(String[] args) throws IOException { // 执行Python脚本 Process process = Runtime.getRuntime().exec("python /path/to/python_script.py"); // 读取Python脚本的输出 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } } ``` 2. 使用Jython库,它是Java与Python的集成引擎。可以在Java代码中直接调用Python函数或执行Python脚本。首先需要导入Jython库,然后创建一个Python解释器,通过Interpreter类的exec方法执行Python脚本或通过Interpreter类的get方法获取Python函数并调用。例如: ```java import org.python.util.PythonInterpreter; public class CallPythonFunc { public static void main(String[] args) { // 创建Python解释器 PythonInterpreter interpreter = new PythonInterpreter(); // 执行Python脚本 interpreter.exec("print('Hello, Python!')"); // 调用Python函数 interpreter.exec("def add(a, b):\n" + " return a + b\n"); interpreter.exec("result = add(2, 3)"); Object result = interpreter.get("result"); System.out.println("Result: " + result); } } ``` 3. 使用第三方库例如JPYTHON或Py4J。这些库可以在Java中直接调用Python函数,并提供了更多高级特性和操作方式。 这些方法根据具体需求可以选择适合自己的方式来调用Python函数。 ### 回答3: 要在Java中调用Python函数,可以使用Java提供的"ProcessBuilder"类来执行Python脚本。 以下是一个简单的示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PythonCaller { public static void main(String[] args) { try { // 创建ProcessBuilder对象,并指定要调用的Python脚本路径 ProcessBuilder pb = new ProcessBuilder("python", "path/to/python_script.py"); // 执行脚本 Process process = pb.start(); // 获取脚本输出 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待脚本执行完成 int exitCode = process.waitFor(); System.out.println("脚本执行完成,退出码:" + exitCode); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } ``` 请替换代码中的"path/to/python_script.py"为你实际的Python脚本路径。 注意,调用Python函数时,需要确保Java运行环境中已经安装了Python,并且Python的可执行文件路径已经加入到了系统的PATH环境变量中。 以上的代码仅是一个简单示例,如果需要传递参数给Python函数,可以通过修改ProcessBuilder对象的命令行参数来实现。具体可以参考ProcessBuilder的文档。 另外,也可以使用类似jython这样的库,它可以在Java中直接解析和执行Python代码,而无需依赖外部进程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值