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__
, andim_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/