在类中调用函数的函数

时间:2018-10-30 14:59:47

标签: python python-3.6

我遇到一个问题,我想拥有一个可以调用或执行类中所有函数的函数。

class example:
    def foo(self):
        print("hi")
    def bar(self):
        print("hello")
    def all(self):
        self.foo()
        self.bar()

还有更好的方法吗?由于我的班级大约有20个函数,因此我只希望一个函数调用所有这些函数。 谢谢

3 个答案:

答案 0 :(得分:1)

请参见How do I get list of methods in a Python class?,以了解如何使用inspect或dir来注册方法

虽然都很丑陋,但检查是首选方法。 您可以通过inspect调用对象的所有方法

import inspect

class A:
    def h(self):
        print ('hellow')

    def all(self):


        for name, f in inspect.getmembers(self, predicate=inspect.ismethod):

            if name != 'all' and not name.startswith('_'):
               f()


a = A()
a.all()

如果更喜欢dir,可以尝试-捕获getattr(self,attr)()

for attr in dir(self):
   try: 
      getattr(self, attr)()
   except Exception:
      pass

答案 1 :(得分:0)

我将其放在一起进行了测试,它似乎可以正常运行,不需要任何库,并且遵循您的原始意图:

class example:
    def __init__(self):
        n = self.__class__.__name__
        self.method_list = [func for func in dir(eval(n)) \
                            if callable(getattr(eval(n), func)) \
                            and func[0]!='_' \
                            and func!='run_all']
    def foo(self):
        print("hi")
    def bar(self):
        print("hello")
    def run_all(self):
        for m in self.method_list:
            runstring = 'self.' + m + '()'
            eval(runstring)  

使用它:

>> a = example()
>> a.run_all()
hello
hi

all是Python命令,因此我将您的方法重命名为run_all

func!='run_all'是必需的,这样您就不会出现令人讨厌的递归情况。

This可让您列出方法,但我对其进行了限制,以便不列出任何私有方法。

self.__class__.__name__获取班级名称

答案 2 :(得分:0)

尽管我不确定这是否是最好的方法,但我建议以下

class AClass():

    def my_method_1(self):
        print('inside method 1')

    def my_method_2(self):
        print('inside method 2')

def run_my_methods():
    executor = AClass()
    all_methods = dir(executor)
    #separate out the special functions like '__call__', ...
    my_methods = [method for method in all_methods if not '__' in method]  
    for method in my_methods:
        eval('executor.%s()'%method)

run_my_methods()

输出为

inside method 1 
inside method 2
相关问题