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

猜你喜欢

转载自www.cnblogs.com/Agoni-7/p/11202757.html