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:
"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.
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)