当我导入正在打印的同一个文件时,为什么 Python 会打印我的输出两次? [英] Why Python print my output two times when I import the same file in which I am printing?

查看:227
本文介绍了当我导入正在打印的同一个文件时,为什么 Python 会打印我的输出两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩 python,因为我是它的初学者.我在 Udacity 在线课程中阅读了以下课程 Parent.

I have been playing around with python as I am a beginner in it. I wrote following class Parent which I was reading from Udacity online course.

继承.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)

如您所见,我导入了当前正在编写类以及打印输出的同一个文件.我得到以下输出两次

As you can see I imported the same file in which I am currently writing class as well as printing the output. I got following output which is twice

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 次,即使我在使用当前文件的导入时打印了一次.后面发生了什么?

When I removed import statement I got the desired output (i.e. output only once ). My question is why python prints this 2 times even though I am printing it once when I use import of current file. What is happening behind?

推荐答案

因为你的程序加载本身!

Because you program load itself!

当你运行inheritance.py时:

When you run inheritance.py:

  • 导入继承:像模块一样加载inheritance.py一次并执行.
  • 执行下一步.
  • import inheritance: load inheritance.py once like a module and execute it.
  • execute next.

所以你的打印语句被执行了两次.

So yours prints statement are executed twice.

您没有导入.

这篇关于当我导入正在打印的同一个文件时,为什么 Python 会打印我的输出两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆