几个 Python 语法糖的实现
生活随笔
收集整理的這篇文章主要介紹了
几个 Python 语法糖的实现
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
受這位小哥(https://github.com/czheo/syntax_sugar_python)的啟發(fā),我照著它的 Usage 實(shí)現(xiàn)了一部分語法糖。
1. compose
實(shí)現(xiàn)compose函數(shù),滿足如下操作:
f = lambda x: x**2 + 1 g = lambda x: 2*x - 1 h = lambda x: -2 * x**3 + 3fgh = compose(f, g, h) # equivalent to `f(g(h(n)))` print fgh(5) # 245026我們可以讓compose返回一個(gè)函數(shù),這個(gè)函數(shù)倒序遍歷compose中的參數(shù),并對(duì)輸入?yún)?shù)調(diào)用該參數(shù)。
def compose(*args):def retFunc(x):i = len(args) - 1while i >= 0:func = args[i]assert(func.__call__)x = func(x)i -= 1return xreturn retFunc2. composable
實(shí)現(xiàn)composable函數(shù),滿足如下操作:
@composable def add2(x):return x + 2@composable def mul3(x):return x * 3@composable def pow2(x):return x ** 2fn = add2 * mul3 * pow2 # equivalent to `add2(mul3(pow2(n)))` print fn(5) # 77composable函數(shù)接受一個(gè)函數(shù),返回一個(gè)封裝后的東西讓其可以通過*來復(fù)合。那我們就創(chuàng)建一個(gè)類來封裝這些東西好了。
class Composable(object):def __init__(self, *args):object.__init__(self)for f in args:assert(f.__call__)self.func = argsdef __call__(self, x):i = len(self.func) - 1while i >= 0:func = self.func[i]assert(func.__call__)x = func(x)i -= 1return xdef __mul__(self, rv):assert(isinstance(rv, Composable))return Composable(*(self.func + rv.func))composable = Composable3.infix
實(shí)現(xiàn)infix,滿足:
@infix def plus(a, b):return a + bprint 1 /plus/ 2 # equivalent to `plus(1, 2)` print 1 /of/ int # equivalent to `isinstance(1, int)` print 1 /to/ 10 # equivalent to `range(1, 11)`我們可以看到,infix函數(shù)接受一個(gè)函數(shù),并把這個(gè)函數(shù)變成中綴。of可以看做isinstance的中綴,to可以看做range的中綴(需要微調(diào))。
我們先把后兩個(gè)定義出來:
of = infix(isinstance) to = infix(lambda x, y: range(x, y + 1))然后實(shí)現(xiàn)infix:
class Infix(object):def __init__(self, f):object.__init__(self)assert(f.__call__)self.func = fself.set = Falsedef __rdiv__(self, i):assert(not self.set)r = Infix(self.func)r.set = Truer.left = ireturn rdef __div__(self, t):assert(self.set)r = self.func(self.left, t)self.set = Falsereturn rdef __call__(self, *args, **kwargs):return self.f(*args, **kwargs)infix = Infix總結(jié)
以上是生活随笔為你收集整理的几个 Python 语法糖的实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Elasticsearch-5.1.2分
- 下一篇: 学习python:练习3.随机生成200