检查函数是否是某个对象的方法 [英] Check if a function is a method of some object
问题描述
如何检查某个函数是否是某个对象的方法?
例如:
<$ p $ (f):
...
check_method(lambda x:x + 1)#>>> False
check_method(SomeClass()。some_method)#>>> True
在'helloworld'示例中的方法中有一些特殊属性(例如'im_self',' __self__'等)。我可以依靠他们还是有一些更好的方法?
使用 inspect.ismethod()
。
文档指出:
如果对象是用Python编写的绑定方法,则返回true。
这意味着它可以像你在Python中定义的类一样工作。但是,对于像 list
之类的内置类或扩展模块中实现的类的方法,它将返回 False
。 p>
How to check if a function is a method of some object?
For example:
def check_method(f):
...
check_method(lambda x: x + 1) # >>> False
check_method(SomeClass().some_method) # >>> True
There are some special attributes in methods in my 'helloworld' example (e.g. 'im_self', '__self__' etc). Can I rely on them or there is some nicer way?
Use inspect.ismethod()
.
The documentation states:
Return true if the object is a bound method written in Python.
This means that it will work as you intend for classes that you define in Python. However, for methods of built-in classes like list
or classes implemented in extension modules it will return False
.
这篇关于检查函数是否是某个对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!