逻辑和调用函数。帮助我理解这段代码

Logic and calling functions. Help me understand this code

我有一些代码基本上是 dict 如何工作的演示。我的问题是,我不确定它何时调用 process_order() 函数。似乎主循环 (go_shopping) 从未调用它,但脚本似乎有效。 go_shopping 函数调用 get_item,但它也不会调用 process_order。我也遇到了 if not process_order(order, cart): 行的问题。在这种情况下 if not 部分是什么意思?那是它调用 process_order 的地方吗?从 print 语句中看起来不像,否则当您将项目添加到购物车字典对象时它应该打印 'if not'。

我是在正确的轨道上还是遗漏了一些简单的东西?

代码:

#!/usr/bin/python3.5

def get_item():
    print("[command] [item] (command is 'a' to add, 'd' to delete, 'q' to quit.)")
    line = input()

    command = line[:1]
    item = line[2:]

    return command, item

def add_to_cart(item, cart):
    if not item in cart:
        cart[item] = 0
    cart[item] += 1

def delete_from_cart(item, cart):
    if item in cart:
        if cart[item] <= 0:
            del cart[item]
        else:
            cart[item] -= 1

def process_order(order, cart):
    command, item = order

    if command == "a":
        add_to_cart(item, cart)
        print('added to cart')
    elif command == "d" and item in cart:
        delete_from_cart(item, cart)
    elif command == "q":
        return False
        print ('end process_order func')
    return True

def go_shopping():
    cart = dict()

while True:
    print ('start main loop')
    order = get_item()
    print ('exited process_order')
        if not process_order(order, cart):
            print ('if not')
            break
    print ('while loop end')
    print (cart)
    print ("Finished!")

go_shopping()

事实上,我不太确定你的问题。但是您似乎很关心调用 process_order 方法的那一刻。

写的时候

if not process_order(order, cart)

必须看到如下(只是加括号):

if (not process_order(order, cart))

所以如果条件 not process_order(order, cart) 为真,您要求 Python 做某事。所以,Python 必须知道表达式 not process_order(order, cart) 的布尔值。

这个表达式由一个一元运算符 not 和一个非初等表达式 process_order(order, cart) 组成。后一个表达式需要求值,所以 Python 到 运行 process_order 方法。

因此,当你写if not process_order(order, cart)的时候,process_order方法确实被执行了