本文介绍了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.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
),具有__call__
的实例或类,则
callable
为true.
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:断言变量是实例方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!