python - 动态创建函数文件中的函数参数

标签 python

我正在尝试编写一个辅助函数来帮助我生成带有函数定义的新文件。以下是部分代码:

def new_function_file(file_name, fun_name, arguments):
  f = open(file_name + ".py", 'w')
  f.write("\tdef " + fun_name + str(("self", ) + arguments) + ":\n")

new_leetcode_file("testfile", "test", ("arr1", "arr2"))

但是,这会在 testfile.py 中生成“def test('self', 'arr1', 'arr2'):”。我想知道如何在不生成单引号的情况下正确解析参数?

最佳答案

格式化打印在这里可能很有用,同时还可以稍微分解一下:

def new_function_file(file_name, fun_name, arguments):

    f = open(file_name + ".py", 'w')

    # expand the arguments and join with "," separators:
    args = ", ".join(arguments) 
    # use formatted print to put it all together nicely:
    write_string = "\tdef {fn}(self, {ar}):\n".format(fn=fun_name, ar=args)

    f.write(write_string)

对于您的演示输入:

new_leetcode_file("testfile", "test", ("arr1", "arr2"))

“writestring”将是:

'\tdef test(self, arr1, arr2):\n'

您可以将其直接写入文件,无需任何其他标点符号。

关于python - 动态创建函数文件中的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31908302/

相关文章:

python - 在 Matplotlib 中以科学计数法显示第一位十进制数字

python - 按年份和 Pandas 中的 id 求和

python - Flask + Flask-Security + Babel 不工作

python - 获取 groupby 和 nlargest 之后的行索引

python - 值错误 : could not convert string to float: '" "'

python - Pandas 从距离矩阵中按 ID 提取列和行

python - 如何使用spyder在单独的窗口中显示视频

python - 如何遍历每个连接的组件标签像素

python - 为什么我的简单线性模型在数据集 g(X) 上学习阈值函数 f(x) = (x > 0) 但在 X 上表现不佳?

python - 如何在 Python 中解析损坏的 XML?