简体   繁体   English

如何调用名称以给定前缀开头的所有函数?

[英]How to call all functions with name starting with given prefix?

In Python how to write such a function which will call all functions in current file with given prefix? 在Python中如何编写这样一个函数,它将使用给定的前缀调用当前文件中的所有函数?

For example: 例如:

def prepare(self):
  # ??? to call prepare_1, prepare_2

def prepare_1(self):

def prepare_2(self):

How to write prepare so it will call all functions started with prepare_ ? 如何编写prepare以便调用所有以prepare_开头的函数?

Use globals to access global namespace, dict.items to iterate over it and callable and str.startswith to identify that function has name you wish and it's callable: 使用全局变量访问全局命名空间,使用dict.items迭代它,并使用callablestr.startswith来识别该函数是否具有您希望的名称并且可以调用:

def prepare(self):
  for key, value in globals().items():
      if callable(value) and key.startswith('prepare_'):
          value()

def prepare_1(self):print 1

def prepare_2(self):print 2

If these functions are methods of a class, use dir(self) to list all attributes of self . 如果这些函数是类的方法,请使用dir(self)列出self所有属性。

class C:

    def prepare(self):
        print(dir(self))
        for name in dir(self):
            if name.startswith('prepare_'):
                method = getattr(self, name)
                method()

    def prepare_1(self):
        print('In prepare_1')

    def prepare_2(self):
        print('In prepare_2')

C().prepare()

Output: 输出:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'prepare', 'prepare_1', 'prepare_2']
In prepare_1
In prepare_2

Update: if you want to call methods from outside of class C: 更新:如果要从C类外部调用方法:

obj = C()
for name in dir(obj):
    if name.startswith('prepare_'):
        m = getattr(obj, name)
        print(m)
        m()

Output: 输出:

<bound method C.prepare_1 of <__main__.C object at 0x7f347c9dff28>>
In prepare_1
<bound method C.prepare_2 of <__main__.C object at 0x7f347c9dff28>>
In prepare_2

It's been asked for, so here's a quick hack: 它被要求了,所以这里是一个快速的黑客:

import functools

class FunctionGroup(object):
   """
       Defines a function group as a list of functions that can be
       executed sequentially from a single call to the function group.

       Use
       @func_group.add
       def my_func(...):
           ...

       to add functions to the function group.

       `func_group(...)` calls the added functions one by one.

       It returns a list of the return values from all evaluated functions.

       Processing terminates when one of the function raises an
       exception and the exception is propagated to the caller.
    """
    def __init__(self):
        self.funcs = []

    def add(self, func):
        self.funcs.append(func)
        return func

    def __call__(self, *args, **kwargs):
        return [
            func(*args, **kwargs) for func in self.funcs
        ]


prepare_group = FunctionGroup()

Note that the __call__() implementation is rather primitive and does nothing to handle exceptions. 请注意, __call__()实现相当原始,不会处理异常。

Usage example: 用法示例:

@prepare_group.add
def prepare_1():
    print "prep 1"

@prepare_group.add
def prepare_2():
    print "prep 2"

prepare_group()

Maybe abused to call methods, of course: 当然,也许滥用来调用方法:

class C(object):
    def m(self):
       pass
c = C()
func_group.add(c.m)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python创建以特定名称开头的所有函数的列表 - Python create a list of all functions starting with specific name 如何使用具有特定前缀的所有函数动态填充数组? - How would I dynamically fill an array with all functions with a specific prefix? 如何从模块的给定函数名称列表中导入函数? - How to import functions from a given list of functions's name of a module? 通过删除给定的前缀模式重命名文件名 - Rename file name by removing given prefix pattern Python:如何使用for循环调用所有函数? - Python: How to use for loop to call all the functions? 当表名以数字开头时,psycopg2如何调用数据库 - psycopg2 how to call database when table name is starting with numbers 给定 function 的 RVA,如何使用 WinAppDbg 挂钩和调用现有函数? - How to use WinAppDbg to hook and call existing functions given RVA of that function? 给定类功能之一,如何在类之外获取类名称 - How to get class name outside a class, given one of its functions Pytest:如何发现以不同前缀开头的文件名? - Pytest: how to discover filenames starting with a different prefix? 获取以 python 中的特定前缀开头的所有环境变量的最佳方法 - Best way to get all environment variables starting with specific prefix in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM