这个例子比较典型,使用了指向函数的变量,有两层封装。
from mxm import container_abcs
from itertools import repeat
def _ntuple(n):
def test_func(x):
if isinstance(x, container_abcs.Iterable): #如果已经是转换后的值,直接返回,不需要再做转换操作
return x
return tuple(repeat(x, n))
return test_func # 返回的是函数
_single = _ntuple(1)
_pair = _ntuple(2) # _pair是指向函数的变量,这里调用的_ntuple 最终是上面定义的 test_func(x)函数,_ntuple参数2传给test_func里面的n,调用_pair时指定的参数才是传递给test_func函数的x值
_triple = _ntuple(3)
_quadruple = _ntuple(4)
思考:
- 这个代码其实是对repeat()函数的进一步封装,而且代码写的好比较健壮,比如对x进行isinstance的判断
- 用下面的方法应该也可以实现,上面的代码搞得更难理解, 只是他多了一层封装,使得可以直接使用一个指向函数的变量和输入一个参数x就能得到想要的结果:
def test_ntuple(x, n):
if isinstance(x, container_abcs.Iterable):
return x
return tuple(repeat(x, n))
- 如果用c代码实现,指需要定义同上的 test_ntuple 函数,然后用宏封装各种不同的参数即可。