如何检查一个python类是否有特定的方法? [英] How to check if a python class has particular method or not?

查看:112
本文介绍了如何检查一个python类是否有特定的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 没有设置方法,我不想考虑它在我的程序的进一步parth我建立类的列表有设置和runtest模块。有没有任何python函数我可以使用相同?

I have such classes in different modules. For eg class A,B,C etc.. In one module I'm considering only classes who have setup and teardown methods. Suppose Class A doesn't have setup method, I don't want to consider it for further parth of my program where I'm building list of classes having setup and runtest module. Is there any python function I can use for the same? What is the correct way to deal with this problem?

推荐答案

您可以使用 hasattr 可调用对类本身(类是对象afterall),例如

You can use hasattr and callable on the classes themselves (classes are objects afterall), i.e. something like

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)]


这种方法可以检测继承:

This methodology does detect inheritance:

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

这篇关于如何检查一个python类是否有特定的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆