亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在類中調用函數的函數

在類中調用函數的函數

料青山看我應如是 2021-07-25 00:20:10
我有一個問題,我想要一個函數來調用或執行類中的所有函數。class example:    def foo(self):        print("hi")    def bar(self):        print("hello")    def all(self):        self.foo()        self.bar()有沒有更好的方法來做到這一點?因為我的班級有大約 20 個函數,而我只想用一個函數來調用所有這些函數。謝謝
查看完整描述

3 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

雖然都是丑陋的,但檢查是首選方法。你可以通過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


查看完整回答
反對 回復 2021-08-03
?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

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


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


查看完整回答
反對 回復 2021-08-03
  • 3 回答
  • 0 關注
  • 211 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號