开发者

Testing for specific method in a Python class

开发者 https://www.devze.com 2023-03-10 23:55 出处:网络
What is the best (or \'Pyth开发者_如何转开发onic\') way to test if a class has a specific method defined?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消