我有一个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程序的代码
使用检查:
或者直接:
或者,如果希望将其作为类方法获取并打印类中的所有方法:
由于@classmethod decorator,允许以下操作:
相关问题 更多 >
编程相关推荐