簡體   English   中英

在類中調用函數的函數

[英]Function to call functions within a class

我有一個問題,我想要一個函數來調用或執行類中的所有函數。

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

有沒有更好的方法來做到這一點? 因為我的班級有大約 20 個函數,而我只想用一個函數來調用所有這些函數。 謝謝

請參閱如何獲取 Python 類中的方法列表? 如何使用檢查或目錄登記方法

雖然都是丑陋的,但檢查是首選方法。 你可以通過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,您可以嘗試 - catch getattr(self, attr)()

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

我把它放在一起並進行了測試,它似乎可以工作並且不需要任何庫並遵循您的原始意圖:

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'是必要的,這樣你就不會發生令人討厭的遞歸情況。

讓你可以列出方法,我限制它只是為了不列出私有方法。

self.__class__.__name__獲取你的類名

雖然我不確定這是否是最好的方法,但我建議如下

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM