1

I am learning python and encountered a problem that I don't understand. I have created a class called Person in a file classes_parent.py

class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

x = Person('John', 'Doe')
x.printname()

I have created a subclass called Student in file classes_child.py:

from classes_parent import Person

class Student(Person):
    pass

s = Student('Alex', 'Doe')
s.printname()

The problem is that the output when I run classes_child.py is this:

John Doe  
Alex Doe  

Why I get both names and not just the student name, i.e. Alex Doe?

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 5
    Because you have `x = Person('John', 'Doe'); x.printname()` in the first file…!? – deceze Feb 20 '20 at 14:46
  • Yes, but they are not part of the class in the first file, just using the class Person. What I understood is that the command: ```from classes_parent import Person``` I just import the class Person, not the whole code included in the file. That's what I am trying to understand. – Daniel Ben-Shabtay Feb 20 '20 at 14:55
  • 1
    The entire file gets executed to define everything you can import. Python can't just pick something out of the middle. – deceze Feb 20 '20 at 14:56

1 Answers1

4

This is why the "if name equals main" boilerplate exists: so you can separate a module's library and main functionality. Change your files like this:

classes_parent.py

class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

if __name__ == '__main__':
    x = Person('John', 'Doe')
    x.printname()

classes_child.py

from classes_parent import Person

class Student(Person):
    pass

if __name__ == '__main__':
    s = Student('Alex', 'Doe')
    s.printname()

Now when you run classes_child.py, it won't run the main code from classes_parent.py, and you'll just get Alex Doe as output.

For more details see:

wjandrea
  • 28,235
  • 9
  • 60
  • 81