Python獲取實例的方法列表,並運行方法

具體需求是這樣的,有一個類,是用做檢查運行環境的,好比python版本,java_home等,具體以下:java

class FlumeEnv(object):
    # use a class to check flume environment
    def __init__(self, zk_ip):
        self._zk_ip = zk_ip
    def check(self):
        flag = True
        # run all method statswith '_check'
    def _check_zk_connection(self):
        try:
            telnetlib.Telnet(self._zk_ip, 2181, 5)
            return True
        except:
            return False
    def _check_java_home(self):
        return True if 'JAVA_HOME' in os.environ else False

google了下找到了解決方法,其中用到了dir和getattr。python

代碼示例:ssh

class A(object):
    def foo(self):
        print 'in foo'
def _foo2(self):
    print 'in private foo2'

在ipython中,getattr得到的已是bound到a的方法了,因此能夠直接使用:google

In [79]: dir(a)
Out[79]: 
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_foo2',
 'foo']
In [80]: [i for i in dir(a) if i.startswith('foo')][0]
Out[80]: 'foo'

In [81]: getattr(a, 'foo')
Out[81]: <bound method A.foo of <__main__.A object at 0x2970550>>

In [82]: getattr(a, 'foo')()
in foo
相關文章
相關標籤/搜索