![](/img/trans.png)
[英]How to check if a block of lines has a particular keyword using python?
[英]How to check if a python class has particular method or not?
class C(Test):
def __init__(self):
print "in C init"
super(C, self).__init__()
def setup(self):
print "\tin C setup"
def runtest(self):
print "\t\tin C runtest"
def teardown(self):
print "\t\t\tin C teardown"
我在不同的模塊中有這樣的類。 例如,類A
, B
, C
等。在一個模塊中,我僅考慮具有設置和拆卸方法的類。 假設類A
沒有設置方法,我不想考慮為我的節目里我建立具有設置和模塊的runTest類名單的進一步PARTH。 我可以使用相同的任何python函數嗎? 解決此問題的正確方法是什么?
我認為這是抽象基類的一種情況。
class Test(metaclass=ABCMeta):
@abstractmethod
def setup(self):
...
@abstractmethod
def teardown(self):
...
@classmethod
def __subclasshook__(cls, C):
if cls is Test:
if (any("setup" in B.__dict__ for B in C.__mro__) and
any("teardown" in B.__dict__ for B in C.__mro___)):
return True
return NotImplemented
這定義了類型Test
和一個__subclasshook__
函數,該函數檢查類是否定義setup()
和teardown()
。 這意味着任何此類都將被視為Test
的子類issubclass()
將為issubclass(C, Test)
返回True
。
當然,您可以使用與__subclasshook__
函數相同的方法手動進行檢查,但是抽象基類提供了一種不錯的(和標准的)方式來定義您想要履行的合同。
您可以在類本身上使用hasattr
和callable
(畢竟,類是對象),例如
if hasattr( C, 'setup' ) and callable( C.setup ):
classes_with_setup.append(C)
或者,就列表理解而言
classes_with_setup=[ U for U in [A,B,C...] if hasattr(U,'setup') and callable(U.setup)]
設置具有這些功能的班級列表。
此方法確實檢測繼承:
In [1]: class A(object):
...: def f(self):
...: print 'hi'
...:
In [2]: class B(A):
...: pass
...:
In [3]: hasattr(A,'f')
Out[3]: True
In [4]: hasattr(B,'f')
Out[4]: True
In [5]: hasattr(B,'f') and callable(B.f)
Out[5]: True
您可以使用getattr
和callable
方法
setup_method = getattr(your_object, "setup_method", None)
if callable(setup_method):
setup_method(self.path.parent_op)
首先檢查對象是否具有名為“ setup_method
”的屬性,然后檢查該屬性是否為方法,然后對其進行調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.