python實現管道

2021-10-20 22:02:20 字數 2917 閱讀 5917

首先,感謝abersheeran ,他也是index.py的作者。看了這段**不禁感嘆:

天才就是99%的汗水+1%的靈感,但沒有這1%的靈感那99%的汗水也是徒勞

大佬的思路我們還是看看就好,能理解就行了,創造出來還是很有難度的

from functools import partial

class

f(partial)

:def

__ror__

(self, other)

:return self(other)

# def __or__(self, other):

# return self(other)

y =range(10

)| f(

filter

,lambda x: x %2)

| f(

sum)

# y = f(sum) | (f(filter, lambda x: x % 2) | range(10))

print

(y)

注釋掉的部分是我狗尾續貂了一把,也是可以執行的。只不過看起來沒那麼管道

我的解讀可能有錯誤的地方,望批評指正。

這幾行**最天才的地方我覺得是繼承了partical類,使得f object is callable,這個可呼叫體現在self(other)上。然後就是重寫了__ror__,這個思路是真的真實,天才的腦迴路!!!

重新審視一下函式呼叫的過程

y =f

(x

)y = f(x)

y=f(x)

將x

xx當做輸入,傳遞給f

ff,得到返回值,這個等價於**中的self(other),而考慮到__ror__運算子的特性,不熟悉一定要去看參考資料。正好可以得到想要的管道寫法。由於|運算子從左到右,再將y重新整理,得到如下**:

y =

range(10

)| partial(

filter

,lambda x: x %2)

y = y | partial(

sum)

所以管道對應的函式為:

y = partial(

filter

,lambda x: x %2)

(range(10

))y = partial(

sum)

(y)

完整**如下:

from functools import partial# as sys_partial

y = partial(

filter

,lambda x: x %2)

(range(10

))y = partial(

sum)

(y)print

(y)

我覺得**中讓人難以理解的地方在於對f的命名,如果像下面這樣,應該不難理解了。

from functools import partial as sys_partial

class

partial

(sys_partial)

:def

__ror__

(self, other)

:return self(other)

# def __or__(self, other):

# return self(other)

y =range(10

)| partial(

filter

,lambda x: x %2)

| partial(

sum)

# y = f(sum) | (f(filter, lambda x: x % 2) | range(10))

print

(y)

_ror_的理解

suppose you write your own integer class, and you want it to work with the built-in integers. you might define__or__

class

myint

(int):

def__or__

(self, other)

:# not a recommended implementation!

return self |

int(other)

so that you can write code like

# because this is equivalent to myint.__or__(myint(6), 7)

myint(6)

|7

however, python wouldn』t know what to do with

# first interpretation is int.__or__(7, myint(6))

7| myint(

6)

becauseint.__or__wouldn』t know how to work with an instance ofmyint. in such a case, python swaps the order of the operands and tries

myint.__ror__(myint(6)

,7)

python管道命令 Python管道和命令列引數

我對python非常陌生,我的工作中有乙個指令碼需要弄清楚。在 我的指令碼解析某個exe檔案的輸出 讓我們稱之為我的工作.exe 它處理另乙個二進位制檔案 我們稱之為processedbinary 現在,我的scrpit需要取乙個processedbinary的名稱並對其進行objdump。我可以看...

Python 管道通訊

管道 雙向通訊 2個程序之間相互通訊 1 from multiprocessing import pipe,process23 deffunc conn1,conn2 4conn2.close 5while true 6try 7 msg conn1.recv 8print msg 9except ...

13 4 15 管道的實現

13.4.15 管道的實現 管道是unix提供的一種在兩個程序間通訊的機制。管道允許乙個程序按照先進先出 first in first out,fifo 的方式向另乙個程序傳送資料。它還可以用於不同程序間的同步。有兩種型別的管道 命名管道和無名管道。就目前的討論而言,可以忽略兩者之間的差別。從本質上...