the following is the code at both ends of getting methods in the class through the inspect
library:
Python2
>>> class A(object):
... def a(self):
... print("a")
... @staticmethod
... def b():
... print("b")
... @classmethod
... def c(cls):
... print("c")
...
>>> import inspect
>>> inspect.getmembers(A, inspect.ismethod)
[("a", <unbound method A.a>), ("c", <bound method type.c of <class "__main__.A">>)]
Python3
>>> class A(object):
... def a(self):
... print("a")
... @staticmethod
... def b():
... print("b")
... @classmethod
... def c(cls):
... print("c")
...
>>> import inspect
>>> inspect.getmembers(A, inspect.ismethod)
[("c", <bound method A.c of <class "__main__.A">>)]
you can see that for classes, the instance method (unbound method) is no longer method
in Python3, but function
.
>>> inspect.getmembers(A, inspect.isfunction)
[("a", <function A.a at 0x10d46e598>), ("b", <function A.b at 0x10d46e620>)]
by consulting the inspect
documents of the two editions, you can see that in python.org/2/library/inspect.html-sharpinspect.ismethod" rel=" nofollow noreferrer "> Python2 :
inspect.ismethod (object)Return true if the object is a bound or unbound method written in Python.
relative to python.org/3.5/library/inspect.html-sharpinspect.ismethod" rel=" nofollow noreferrer "> Python3 :
inspect.ismethod (object)
Return true if the object is a bound method written in Python.
ismethod
no longer contains unbound method.
is this a general difference from Python2 to Python3? Unfortunately, such an important distinction is not mentioned in most articles such as "Differences between Python2 and Python3".