如何测试一个对象是一个函数还是一个未绑定的方法?
作者:互联网
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
??
解决方法:
未绑定的方法将__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中,未绑定的方法已经消失;访问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,introspection 来源: https://codeday.me/bug/20190725/1530121.html