【问题标题】:Creating a list of all functions from .py file and run random of them从 .py 文件创建所有函数的列表并随机运行它们
【发布时间】:2019-05-03 13:54:17
【问题描述】:

我想在 .py 文件中创建一个所有函数的列表,然后随机使用这些函数。 我已经使用 dir() 创建了一些列表,但无法运行。

带有函数file.py的文件:

def f1:
   # some code
def f2:
   # some code
def f3:
   # some code

另一个脚本:

functions = dir(file)
random.choice(functions)()

显示这个错误

TypeError: 'str' object is not callable

【问题讨论】:

标签: python list function


【解决方案1】:

假设file1.py中的所有函数都只包含没有参数的函数或只有默认值参数的函数,那么

如果file1.py

def f1():
    print ("f1")

def f2():
    print ("f2")

def f3():
    print ("f3")

def f4(i=0):
    print ("f4")

另一个脚本是:

import file1
from inspect import getmembers, isfunction
import random

functions_list = [o for o in getmembers(file1) if isfunction(o[1])]
random.shuffle(functions_list)

for f in functions_list:
    f[1]()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 2021-09-23
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多