我在一个函数调用中看到了一个“管道”字符 (|
):
res = c1.create(go, come, swim, "", startTime, endTime, "OK", ax|bx)
ax|bx
中的竖线的含义是什么?
我在一个函数调用中看到了一个“管道”字符 (|
):
res = c1.create(go, come, swim, "", startTime, endTime, "OK", ax|bx)
ax|bx
中的竖线的含义是什么?
这也是并集运算符
set([1,2]) | set([2,3])
这将导致 set([1, 2, 3])
它是整数的按位或运算。例如,如果ax
或bx
中有一个或两个都为1
,则结果为1
,否则为0
。它也可以用于其他整数,例如15 | 128 = 143
,即二进制下的00001111 | 10000000 = 10001111
。
__or__
方法与第二个操作数进行或运算,因此您可以为自己的类定义其行为。 - Dawn Drescher是的,以上所有答案都是正确的。
虽然您可能会发现"| "有更多奇特的用例,但如果它是一个类使用的重载运算符,例如
https://github.com/twitter/pycascading/wiki#pycascading
input = flow.source(Hfs(TextLine(), 'input_file.txt'))
output = flow.sink(Hfs(TextDelimited(), 'output_folder'))
input | map_replace(split_words, 'word') | group_by('word', native.count()) | output
在这种特定的用例中,管道符“|”可以被看作是Unix管道符。但是我同意,在Python中,“|”更常用于按位操作符和并集运算符。>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
>>> e = {'cheese': 4, 'nut': 5}
>>> d | e
{'spam': 1, 'eggs': 2, 'cheese': 4, 'nut': 5} # comment 1
>>> e | d
{'cheese': 3, 'nut': 5, 'spam': 1, 'eggs': 2} # comment 2
注释 1 如果一个键在两个操作数中都出现了,那么最后出现的值(即右操作数中的值)将获胜 --> 'cheese':4 而不是'cheese':3
注释 2 cheese出现了两次,所以选择第二个值,因此d [cheese] = 3
|
运算符最初用于执行位或操作。这里有一个关于位运算的教程。f'{0b1100 | 0b1010 :04b}' == '1110'
|
可以通过实现函数__or__
(和__ror__
)来进行重载。任何Python库,无论是标准库还是用户库,都可以重载任何运算符(例如,存档的PyCascading)。set
和dict
,通过重载|
来定义并集和合并操作。特别是在Python 3.9和PEP 584中,对dict
和其他标准库类型引入了重载的|
和其他运算符。# sets; | does union of sets
# the order does not matter, i.e., the operation is commutative
{1, 2} | {2, 3} == {1, 2, 3}
{2, 3} | {1, 2} == {1, 2, 3}
# dicts; | does "merging" of dicts
# the order does matter, i.e., the operation is NOT commutative
{'a': 1, 'b': 2} | {'b': 99, 'c': 3} == {'a': 1, 'b': 99, 'c': 3}
{'b': 99, 'c': 3} | {'a': 1, 'b': 2} == {'a': 1, 'b': 2, 'c': 3}
|
运算符的例子是在 Python LangChain 库 中用于 链式/管道操作。这是 LangChain 如何重载该运算符的精确代码。# LangChain chained sequence of components
chain = prompt | model | output_parser