为什么在导入打印的同一文件时Python会将输出打印两次?

2024-06-01 01:36:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在玩python,因为我是python的初学者。我写了下面的《家长》一书,这是我从Udacity在线课程中读到的

heritation.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会打印这两次,即使我在使用当前文件的导入时只打印了一次。背后发生了什么


Tags: 文件ofnameselfchildnumbercolorparent
1条回答
网友
1楼 · 发布于 2024-06-01 01:36:00

因为你可以自己加载程序

运行heritation.py时:

  • import inheritance:像模块一样加载一次heritation.py并执行它
  • 执行下一步

所以你的prints语句执行两次

您没有导入

相关问题 更多 >