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?

2

1 Answer 1

5

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.

2
  • 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. May 25, 2015 at 9: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. docs.python.org/3/library/__main__.html May 25, 2015 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.