zoukankan      html  css  js  c++  java
  • python -- 判断函数和方法

    7.7.1 通过打印函数(方法)名确定

    def func():
        pass
    print(func)  # <function func at 0x00000260A2E690D0>
    
    class A:
        def func(self):
            pass
    print(A.func) # <function A.func at 0x0000026E65AE9C80>
    obj = A()
    print(obj.func)  # <bound method A.func of <__main__.A object at 0x00000230BAD4C9E8>>
    

    7.7.2 通过types模块验证

    • 类名调用类中的方法,是一个函数
    • 对象调用类中的方法,是一个方法
    from types import FunctionType
    from types import MethodType
    
    def Foo():
        pass
    
    class A:
        def func(self):
            pass
        
    obj = A()
    
    print(isinstance(Foo,FunctionType)) # True
    print(isinstance(A.func,FunctionType)) # True
    print(isinstance(A.func,MethodType) # False
    print(isinstance(obj.func,FunctionType)) # False
    print(isinstance(obj.func,MethodType)) # True     
    

    7.7.3 静态方法是函数

    • 类名和对象调用都是函数
    • 类方法:类名和对象调用都是方法
    from types import FunctionType
    from types import MethodType
    
    class A:
        
        def func(self):
            pass
        
        @classmethod
        def func1(self):
            pass
        
        @staticmethod
        def func2(self):
            pass
    obj = A()
    
    # 静态方法其实是函数
    print(isinstance(A.func2,FunctionType))  # True
    print(isinstance(obj.func2,FunctionType))  # True
    

    7.7.4 函数与方法的区别 (前两条重点)

    • 函数:全部都是显性传参(手动传参)

    • 方法:存在隐性传参(自动传参 -- 对象调用类中的方法,自动将对象传给self,类方法)

      函数跟对象无关

      方法可以操作类内部的数据

      方法跟对象是关联的 例如: 字符串的方法中 s.strip()

      Java 中只有方法, C 中只有函数 C++取决于是都在类中

  • 相关阅读:
    POJ3678 KATU PUZZLE
    poj3321(codevs1228)苹果树
    codevs 1955 光纤通信 USACO
    codevs 1027 姓名与ID
    codevs 1051 接龙游戏
    洛谷 P1717 钓鱼
    codevs 1062 路由选择
    洛谷 P1083 借教室
    codevs 2596 售货员的难题
    Vijos 1053 easy sssp
  • 原文地址:https://www.cnblogs.com/Agoni-7/p/11202757.html
Copyright © 2011-2022 走看看