簡體   English   中英

為什么導入的文件又產生一個重復的結果?

[英]Why does imported file produce one more repeated result?

我已經制作了一個要導入的文件,比方說pizza.py。

def make_pizza(size, *toppings): 
    """Summarize the pizza we are about to make."""
    print("\nMaking a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

我在這個程序中調用了模塊,比如makeing_pizza.py

import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

我所做的任何設置都會產生重復的結果嗎?

以下是一個重復的結果。

Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

因此,從這兩個腳本中,是什么使結果產生了另一個重復的收益?

您需要將所有代碼包含在main塊中,以避免在導入期間執行它,如下所示:

def make_pizza(size, *toppings): 
    """Summarize the pizza we are about to make."""
    print("\nMaking a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza(16, 'pepperoni')  # this line will execute during import because it is not within main block
if __name__ == "__main__":
    make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')  # this line is under main block hence it will only execute when you execute this file not on import

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM