我一直在玩python,因为我是初学者。我写了以下课程的家长,我正在读Udacity在线课程。
inheritance.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打印这两次,即使我在使用当前文件导入时打印一次。背后发生了什么?
答案 0 :(得分:2)
因为您自己编程加载!
运行inheritance.py时:
import inheritance
:像模块一样加载inheritance.py并执行它。所以你的print语句会被执行两次。
您没有导入。