查看一个 '函数' 到底是【函数】还是【方法】

发布时间 2023-11-30 15:10:47作者: wellplayed

需要用到FunctionTypeMethodType

from types import FunctionType, MethodType

 

准备测试用代码

写一个函数:

def add():
    pass

写一个类:

class Person:
    
    def run(self):
        pass

    @classmethod
    def xx(cls):
        pass

    @staticmethod
    def yy():
        pass

 

使用方法

print(isinstance(add,FunctionType)) # True
print(isinstance(add,MethodType)) # False

 

总结

方法:会自动传值的就是方法,类中绑定静态对象的方法也是函数
函数:需要传入的值一一对应,类调用绑定给对象的方法时不会自动传值,因此也是函数