目录
一、定义
函数:普通 def 出来,若存在参数,需要手动传参的函数。
方法:类内 def 出来,不需要手动传 self 参数 的函数。
注意!若使用类直接调用类内方法,该对象为函数。
魔法方法:类内定义,以__开头的方法,可作为私有属方法存在。例:__init__,__call__等
偏函数:基于functools内部模块内partial组件实现的函数。偏函数返回一个新函数。
# 偏函数的第二个部分(可变参数),按原有函数的参数顺序进行补充,参数将作用在原函数上,最后偏函数返回一个新函数 from functools import partial def test(a,b,c,d): return a+b+c+d tes=partial(test,1,2) print(tes(3,4))
二、方法和函数的具体举例及其辨别方式
from types import MethodType,FunctionType def func(): pass class Foo(object): def fetch(self): pass # 函数 func() Foo.fetch('xxx') # 方法 foo = Foo() foo.fetch() # 使用内部ininstance方法进行判断 # 基于MethodType类的为方法 # 基于FunctionType类的为函数 print(isinstance(Foo.fetch,MethodType)) print(isinstance(Foo.fetch,FunctionType)) # True obj = Foo() print(isinstance(obj.fetch,MethodType)) # True print(isinstance(obj.fetch,FunctionType))