python三元运算符的奇怪行为

时间:2017-07-07 13:58:29

标签: python-3.x if-statement

我编写了一个简单的堆类,而不是相关的。在类的init函数中,我编写了以下代码

def __init__(self, fn=None):
    self.heap = ["start"]  
    self.size_ = 0
    # condition of heap for no change to happen. default is min heap
    self.fn = lambda parent_, child_: (parent_ < child_) if fn is None else fn

当我使用self.fn函数时(当我传递参数而不是None时)它将不起作用。例如,当我说

maxHeap = BinaryQueue(fn=lambda x, y: x > y)
print(maxHeap.fn(3, 4))

将输出<function <lambda> at 0x00000135EB76D1E0>

如果我写

def __init__(self, fn=None):
    self.heap = ["start"] 
    self.size_ = 0
    # condition of heap for no change to happen. default is min heap
    if fn is None:
        self.fn = lambda parent_, child_: parent_ < child_
    else:
        self.fn = fn

False

开始,它会正确输出3>4 is False

为什么三元版本不起作用的任何想法? (使用python 3.6)

0 个答案:

没有答案