zoukankan      html  css  js  c++  java
  • 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. 实例方法,如果是实例访问.就是⽅法.如果是类名访问就是函数.
    
    """
    

      

  • 相关阅读:
    常用分页插件
    sessionStorage二种存值取值的方法
    $(this).index()与$(obj).index(this)的区别
    每次移1px的无缝轮播图
    为什么全局变量在赋值之前调用会报错
    Number()、parseInt()和parseFloat()的区别
    JSON.parse()与JSON.stringify()
    HDU
    出现负数的01背包问题
    HDU
  • 原文地址:https://www.cnblogs.com/fanghongbo/p/9966176.html
Copyright © 2011-2022 走看看