Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
im_self attribute (only Python 2)
In python 3 the
__self__
attribute is only set on bound methods. It's not set toNone
on plain functions (or unbound methods, which are just plain functions in python 3).Use something like this:
The chosen answer is valid in almost all cases. However when checking if a method is bound in a decorator using chosen answer, the check will fail. Consider this example decorator and method:
The
print
statement in decorator will printFalse
. In this case I can't find any other way but to check function parameters using their argument names and look for one namedself
. This is also not guarantied to work flawlessly because the first argument of a method is not forced to be namedself
and can have any other name.User-defined methods:
In Python 2.6 and 3.0: