繁体   English   中英

如何检查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"

我在不同的模块中有这样的类。 例如,类ABC等。在一个模块中,我仅考虑具有设置和拆卸方法的类。 假设类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__函数相同的方法手动进行检查,但是抽象基类提供了一种不错的(和标准的)方式来定义您想要履行的合同。

您可以在类本身上使用hasattrcallable (毕竟,类是对象),例如

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

您可以使用getattrcallable方法

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM