簡體   English   中英

如何通過其成員函數名稱調用Python實例的非特定方法?

[英]How can I call a Python instance's unspecific method by its member function name?

class worker:
    def foo(self):
        pass
    def foo1(self):
        pass
    def foo2(self)
        pass

worker實例將有幾個foo*格式的成員函數( foo*函數的數量是未知的,因為它是由其他開發人員提供的。如何在用戶添加時編寫一個函數來調用所有worker的foo *成員函數而不進行修改新的foo *功能?

我可以通過調用dir()來獲取所有工作者實例函數名列表,但是它的元素是str,我無法通過字符串值來運行工作器實例。 我怎么能解決這個問題?

使用getattr()函數從實例訪問任意屬性。 使用dir()函數列出類的所有(繼承)屬性。 結合這些使得:

foo_attributes = [attr for attr in dir(instance) if attr.startswith('foo')]
for name in foo_attributes:
    attr = getattr(instance, name)
    if callable(attr):
        attr()

我在這里使用了callable()函數來確保該屬性確實是一個方法。

快速演示:

>>> class worker:
...     def foo(self):
...         print "Called foo"
...     def foo1(self):
...         print "Called foo1"
...     def foo2(self):
...         print "Called foo2"
... 
>>> instance = worker()
>>> foo_attributes = [attr for attr in dir(instance) if attr.startswith('foo')]
>>> for name in foo_attributes:
...     attr = getattr(instance, name)
...     if callable(attr):
...         attr()
... 
Called foo
Called foo1
Called foo2

暫無
暫無

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

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