函数和方法
# 函数就是普通函数,有几个值就要传几个值
# 方法[面向对象]是绑定给对象,类,绑定给谁谁来调用,会自动传值,谁来调用就会把谁传入
#总结:只要能自动传值,就是方法,有几个值传几个值就是函数
# 就是个函数
def add(a, b):
return a + b
class Person:
# 方法:绑定给对象的【不一定是方法】
def speak(self):
print('人说话')
@classmethod
def test(cls):
print('类的绑定方法')
@staticmethod
def ttt():
print('static')
p = Person()
# p.speak() # 能自动传值
# 如何确定到底是函数还是方法
from types import MethodType, FunctionType
print(isinstance(add, MethodType)) # False add 是个函数,不是方法
print(isinstance(add, FunctionType)) # True
print(isinstance(p.speak, MethodType)) # 方法
print(isinstance(p.speak, FunctionType)) # 不是函数
print(isinstance(Person.speak, FunctionType)) # 类来调用,它就是普通函数,有几个值就要传几个值
print(isinstance(Person.speak, MethodType)) # 不是方法了
Person.speak(p) # 普通函数
print(isinstance(Person.test, FunctionType)) # 不是函数
print(isinstance(Person.test, MethodType)) # 类来调用,类的绑定方法
print(isinstance(p.test, FunctionType)) # 不是函数
print(isinstance(p.test, MethodType)) # 对象来调用,类的绑定方法
Person.test()
print(isinstance(p.ttt, FunctionType)) # 静态方法,本质就是个函数,有几个值就要传几个值
print(isinstance(p.ttt, MethodType))
偏函数
# python内置给咱们一个偏函数,可以把函数包裹一下,提前传参
from functools import partial
def add(a, b, c):
return a + b + c
# 正常使用
# res=add(4,5,6)
# print(res)
# 使用偏函数,提前传值
res = partial(add, 4, 5)
print(res) # functools.partial(<function add at 0x000002C4025C71F0>, 4)
print(res(6))