具体需求是这样的,有一个类,是用作检查运行环境的,比如python版本,java_home等,具体如下:
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。
代码示例:
class A(object):
def foo(self):
print 'in foo'
def _foo2(self):
print 'in private foo2'
在ipython中,getattr获得的已经是bound到a的方法了,所以可以直接使用:
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