day17 Python 区分函数和方法 FunctionType 、MethodType 和 type

from types import FunctionType, MethodType


class Car(object):

    def __init__(self):
        pass

    def run(self):
        print("my car can run!")

    @staticmethod
    def fly(self):
        print("my car can fly!")

    @classmethod
    def jumk(cls):
        print("my car can jumk!")


c = Car()

# type(obj) 表示查看obj是由哪个类创建的.

# 实例方法
print(type(c.run))  # <class 'method'>
print(type(Car.run))  # <class 'function'>

# 静态方法
print(type(c.fly))  # <class 'function'>
print(type(Car.fly))  # <class 'function'>

# 类方法,因为类在内存中也是对象,所以调用类方法都是方法类型
print(type(c.jumk))  # <class 'method'>
print(type(Car.jumk))  # <class 'method'>


# 使用FunctionType, MethodType 来判断类型
# 实例方法
print(isinstance(c.run,MethodType)) # True
print(isinstance(Car.run,FunctionType)) # True

# 静态方法
print(isinstance(c.fly,FunctionType)) # True
print(isinstance(Car.fly,FunctionType)) # True

# 类方法
print(isinstance(c.jumk,MethodType))   # True
print(isinstance(Car.jumk,MethodType))   # True


"""结论
1. 类⽅法.不论任何情况,都是⽅法.
2. 静态方法,不论任何情况.都是函数
3. 实例方法,如果是实例访问.就是⽅法.如果是类名访问就是函数.

"""