【发布时间】:2011-09-09 10:06:36
【问题描述】:
测试一个类是否定义了特定方法的最佳(或“Pythonic”)方法是什么?
这两个都有效,但在第二个中感觉不“正确”,我只是尝试访问它并捕获异常(如果它不存在)。
有没有更好/更正确的方法?
class TestClass(object):
def TestFunc(self):
pass
if 'TestFunc' in dir(TestClass):
print 'yes'
else:
print 'No'
try:
if TestClass.__getattribute__(TestClass, 'TestFunc'):
print 'yes'
except:
print 'No'
【问题讨论】: