What is the best (or 'Pyth开发者_如何转开发onic') way to test if a class has a specific method defined?
Both of these work but don't feel 'correct' in that in the second one, I just try to access it and trap for an exception if it doesn't exist.
Is there a better / more correct way?
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'
Use hasattr
:
class Foo(object):
def bar():
pass
assert hasattr(Foo, 'bar')
If you really mean to test whether the attribute is a method, you could do this:
assert hasattr(Foo, 'bar') and callable(getattr(Foo, 'bar'))
You're close.
It's Easier to Ask Forgiveness than to Ask Permission.
try:
testClassInstance.testFunc()
except AttributeError:
pass # Ask forgiveness.
Don't "pre-test" for things like this. Assume they exist and cope with their absence.
精彩评论