将类中的方法存储在新fi中

2024-09-28 01:25:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python项目,其中大多数业务逻辑都在类方法中。现在我想在一个独立的项目中重用一些类方法

是否可以编写一个类方法,将其他类方法“导出”到一个新的Python文件中,以创建一个包含一组导出函数的脚本

class MyObject:

    def __init__(self, value):
        self.value = value

    def method1(self):
        # the method I want to use in another project

    def method2(self):
        ...

    def method3(self):
        ...

    def export_method(self, target_file):
        # export the code of method1 to a new python file

当我运行export_method('myfile.py')时,我想创建一个包含method1作为函数的Python文件:

def method1():
    ...

注意:我知道软件应该被重组,并且method1应该在另一个模块中,在这个模块中可以从其他项目导入。我只是好奇是否有一种简单的方法可以从代码本身访问Python程序的代码


Tags: 模块文件theto项目方法函数代码
1条回答
网友
1楼 · 发布于 2024-09-28 01:25:20

使用检查:

或者直接:

import inspect
lines = inspect.getsource(MyObject.method1)
with open(target_file, 'w') as file:
    file.write(lines)

或者,如果希望将其作为类方法获取并打印类中的所有方法:

import inspect

class MyObject:

    def __init__(self, value):
        self.value = value

    def method1(self):
        pass

    def method2(self):
        pass

    def method3(self):
        pass

    @classmethod
    def export_method(cls, target_file):
        # export the code of method1 to a new python file
        methods = inspect.getmembers(cls, predicate=inspect.ismethod)
        with open(target_file, 'w') as f:
            for method in methods:
                lines = inspect.getsource(method[1])
                f.write(lines)

由于@classmethod decorator,允许以下操作:

MyObject.export_method('code.txt')

相关问题 更多 >

    热门问题