如何检查变量是否是实例方法?我正在使用Python 2.5。
像这样的事情:
class Test:
def method(self):
pass
assert is_instance_method(Test().method)
inspect.ismethod http://docs.python.org/library/inspect.html#inspect.ismethod是你想知道的,如果你确实有一个方法,而不仅仅是你可以调用的东西。
import inspect
def foo(): pass
class Test(object):
def method(self): pass
print inspect.ismethod(foo) # False
print inspect.ismethod(Test) # False
print inspect.ismethod(Test.method) # True
print inspect.ismethod(Test().method) # True
print callable(foo) # True
print callable(Test) # True
print callable(Test.method) # True
print callable(Test().method) # True
callable
如果参数是方法、函数(包括lambda
s),一个实例__call__
或一个班级。
方法具有与函数不同的属性(例如im_class
and im_self
)。所以你要
assert inspect.ismethod(Test().method)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)