Python:断言该变量是实例方法? [英] Python : Assert that variable is instance method?
本文介绍了Python:断言该变量是实例方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检查变量是否是实例方法?我使用的是 python 2.5.
How can one check if a variable is an instance method or not? I'm using python 2.5.
像这样:
class Test:
def method(self):
pass
assert is_instance_method(Test().method)
推荐答案
inspect.ismmethod
是你想知道你是否确实有一个方法,而不仅仅是你可以调用的东西.
inspect.ismethod
is what you want to find out if you definitely have a method, rather than just something you can call.
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
如果参数是方法、函数(包括 lambda
s)、带有 __call__
的实例,则
callable
为真,或者一类.
callable
is true if the argument if the argument is a method, a function (including lambda
s), an instance with __call__
or a class.
方法具有与函数不同的属性(例如 im_class
和 im_self
).所以你想要
Methods have different properties than functions (like im_class
and im_self
). So you want
assert inspect.ismethod(Test().method)
这篇关于Python:断言该变量是实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文