Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why did I get a "None" value of the parameter in subclass?

I’m new to python (and coding) and I’ve been trying to expand my knowledge by youtube tutorials. When watching a chapter about classes I have created a class and a sub class and I don’t know why I get the results as they are. Can you help me?

This is my code:

class Person:
    def __init__(self, name, age, height):
        self.name = name
        self.age = age
        self.height = height

    def print_info(self):
        print(self.name + ", age " + self.age + ", height " + self.height + "cm.")


class Employee(Person):
    def  __init__(self, name, age, height, id_number):
        Person.__init__(self, name, age, height)
        self.id_number = id_number

    def print_employee_info(self):
        print(str(Person.print_info(self)) + self.id_number)

john = Employee("John", "20", "182", "2230")
john.print_employee_info()

I expected it to print:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"John, age 20, height 182cm.2230"

What I got is:

"John, age 20, height 182cm 
None2230"

So I believe it that it prints in new line "None2230" because I call the method Person.print_info(self) ?

What I don’t know is why there is "None" added to id_number and how can I fix this?

If anything else bothers you, just write it down I’d like to learn.

Thanks a lot for the answers.

Much appreciated.

>Solution :

You want your print_info method to return a string rather than printing it. Try changing it to this:

    def print_info(self):
        return self.name + ", age " + self.age + ", height " + self.height + "cm."

Then your print_employee_info can just be

    def print_employee_info(self):
        print(self.print_info() + self.id_number)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading