python方法与函数

实际上方法和函数是不一样的,下面我们了解一下方法与函数的区别

方法与函数的区别

如何确定函数与方法

  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>>
  1. 通过types模块验证
from types import FunctionType
from types import MethodType

def func():
    pass


class A:
    def func(self):
        pass

obj = A()


print(isinstance(func,FunctionType))  # True
print(isinstance(A.func,FunctionType))  # True
print(isinstance(obj.func,FunctionType))  # False
print(isinstance(obj.func,MethodType))  # True

需要注意的是,静态方法实际上是函数

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

函数与方法的区别(了解)

  1. 函数的是显式传递数据的。如我们要指明为len()函数传递一些要处理数据
  2. 函数则跟对象无关
  3. 方法中的数据则是隐式传递的
  4. 方法可以操作类内部的数据
  5. 方法跟对象是关联的。如我们在用strip()方法是,是不是都是要通过str对象调用,比如我们有字符串s,然后s.strip()这样调用。是的,strip()方法属于str对象

猜你喜欢

转载自blog.csdn.net/m0_47438967/article/details/120581631