antonmuhin at sendmail.ru
Sat Apr 19 20:00:09 CEST 2003
> Relatively new to Python and I thought I would teach myself the
> language by building a test harness. After I'm done, I will probably
> be throwing it away in favor of Pyunit, but it seemed like a good way
> to learn some of the fiddly bits.
> Fiddly bits such as "can this object do that?" In my test code, I
> want to test whether or not a given class *or* instance of that class
> can execute a particular method (i.e., if it has or inherits the
> method). For example, one way (in Perl), to test if object "$foo" can
> execute an arbitrary method would be:
> if ( $foo->can($some_method) )
> For the life of me, I can't figure out the equivalent in Python. I
> suppose I could do:
> if some_method in Foo.__dict__:
> But that doesn't tell me whether or not "some_method" is a method.
> Further, if I have an instance of a class, that doesn't seem to work.
> I've been searching through the docs, but I can't quite figure this
> I'm a clueless newbie here, so please be kind :)
There are several ways to do it.
1. More Pythonic IMHO:
foo = Foo()
except (AttributeError, TypeError), e:
print "Failed. Message @%s@" % e, "Type: %s" % e.__class__.__name__
2. Look at hasattr and callable functions
foo = Foo()
foo.xxx = 239
print hasattr(foo, "absent_method") # false
print hasattr(foo, "xxx") # true
print callable(foo.xxx) # false
print callable(foo.bar) # true
Sure, there are circumstances, then one of methods is better.
BTW, look for a thread about typing in Python---you might find
interesting information there.
More information about the Python-list