0

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.

inheritance.py file

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

But I was expecting it only once

Child Constructor Called
Parent Constructor Called
Cyrus
5

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?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Rajesh Surana
  • 883
  • 1
  • 10
  • 15

1 Answers1

3

Because you program load itself!

When you run inheritance.py:

  • import inheritance: load inheritance.py once like a module and execute it.
  • execute next.

So yours prints statement are executed twice.

You do not have import.

Olivier Pirson
  • 737
  • 1
  • 5
  • 24
  • Do you mean to say that when I execute any program of python, all the imported modules are executed first and then my current file is executed in which I am using those modules? Why didn't it go in infinite loop then? Like when it was executing inheritance.py because it is imported, it again has inheritance.py imported which should trigger infinite loop of printing the output. – Rajesh Surana May 25 '15 at 09:10
  • Yes. And your program import itself. Do not do that. In a module you can add: `if __name__ == "__main__": ...` So, ... will not execute when module is imported. https://docs.python.org/3/library/__main__.html – Olivier Pirson May 25 '15 at 09:16