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++取决于是都在类中

  • 相关阅读:
    Windows10 iis10 arr webfarm
    两个command的疑惑
    关于controller和apicontroller的跨域实现过滤器的不同
    抽象工厂
    c# 字体库跨域解决
    c# 父类的引用指向子类的实例
    垂直居中
    扇形导航
    2D变换
    京东放大镜效果
  • 原文地址:https://www.cnblogs.com/Agoni-7/p/11202757.html
Copyright © 2011-2022 走看看