python之类中如何判断是函数还是方法

通常我们认为在类中的函数为方法,类外面声明def为函数,这种说法有点片面

方法1:

class Work(object):
    def show(self):
        print("执行show方法")

work = Work()
print(Work.show)
print(work.show)

结果:
<function Work.show at 0x000001CC55BC5268>
<bound method Work.show of <__main__.Work object at 0x000001CC55C2F240>>

可以看出通过类方法调用为函数,通过实例化对象调用为方法

方法2:

from types import MethodType,FunctionType
print(isinstance(Work.show,FunctionType))
print(isinstance(Work.show,MethodType))
print(isinstance(work.show,FunctionType))
print(isinstance(work.show,MethodType))

结果:
True
False
False
True

 可以用内置的isinstance 来判断

原文地址:https://www.cnblogs.com/xcsg/p/10551114.html