簡體   English   中英

當我導入正在打印的同一個文件時,為什么 Python 會打印我的輸出兩次?

[英]Why Python print my output two times when I import the same file in which I am printing?

我一直在玩 python,因為我是它的初學者。 我在 Udacity 在線課程中閱讀了以下課程 Parent。

繼承.py文件

import inheritance  # Why this import statement causing output two times?

class Parent():
    def __init__(self, last_name, eye_color):
        print("Parent Constructor Called")
        self.last_name = last_name
        self.eye_color = eye_color

class Child(Parent):
    def __init__(self, last_name, eye_color, number_of_toys):
        print("Child Constructor Called")
        Parent.__init__(self, last_name, eye_color)
        self.number_of_toys = number_of_toys

miley_cyrus = Child("Cyrus", "Blue", 5)
print(miley_cyrus.last_name)
print(miley_cyrus.number_of_toys)

如您所見,我導入了當前正在編寫類以及打印輸出的同一個文件。 我得到了以下輸出,這是兩次

Child Constructor Called
Parent Constructor Called
Cyrus
5
Child Constructor Called
Parent Constructor Called
Cyrus
5

但我只期待一次

Child Constructor Called
Parent Constructor Called
Cyrus
5

當我刪除 import 語句時,我得到了所需的輸出(即只輸出一次)。 我的問題是為什么 python 會打印 2 次,即使我在使用當前文件的導入時打印了一次。 后面發生了什么?

因為你程序加載本身!

當你運行inheritance.py時:

  • import inheritance :像模塊一樣加載inheritance.py一次並執行它。
  • 接下來執行。

所以你的打印語句被執行兩次。

你沒有導入。

暫無
暫無

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

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