python - 如何测试一个对象是一个函数还是一个未绑定(bind)的方法?

标签 python introspection

def is_unbound_method(func):
    pass

def foo(): pass

class MyClass(object):
    def bar(self): pass

我可以在 is_unbound_method 中放入什么

is_unbound_method(foo) == False
is_unbound_method(MyClass().bar) == False
is_unbound_method(MyClass.bar) == True

??

最佳答案

未绑定(bind)的方法将 __self__ 设置为 None:

def is_unbound_method(func):
    return getattr(func, '__self__', 'sentinel') is None

演示:

>>> foo.__self__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__self__'
>>> is_unbound_method(foo)
False
>>> MyClass.bar.__self__
>>> is_unbound_method(MyClass.bar)
True
>>> MyClass().bar.__self__
<__main__.MyClass object at 0x106c64a50>
>>> is_unbound_method(MyClass().bar)
False

该属性也可用作 .im_self,但 __self__ 是向前兼容的。

请注意,在 Python 3 中,未绑定(bind)方法已不存在;访问 MyClass.bar 返回函数对象。因此上面的函数将总是返回False

参见 Datamodel documentation ,在用户定义的方法部分:

Special read-only attributes: im_self is the class instance object, im_func is the function object

[...]

Changed in version 2.6: For Python 3 forward-compatibility, im_func is also available as __func__, and im_self as __self__.

[...]

When a user-defined method object is created by retrieving a user-defined function object from a class, its im_self attribute is None and the method object is said to be unbound.

关于python - 如何测试一个对象是一个函数还是一个未绑定(bind)的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25083220/

相关文章:

Python 线程 self._stop() 'Event' 对象不可调用

python - 刷新装饰器

rust - 在运行时检查 Rust 特性

python - 在 Python 中更改对运行时函数的引用

python - 来自 Spark 数据帧的 block topandas

python - 将文本输入到 codemirror python selenium 的文本区域

python - 使用 Anaconda (Python) 在 Windows 上安装 Pyomo

java - 我可以将注释注入(inject)到 pojo 中吗

c - 如何在 Perl API 中内省(introspection)正则表达式

python - 如何列出 Python 2.5 模块中的方法?