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.
CodePudding user response:
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)
CodePudding user response:
print_info(self) does not return anything (returns None). If you want your code to work you should do soemthing like:
def get_info(self):
return self.name ", age " self.age ", height " self.height "cm."
and then
def get_employee_info(self):
return str(Person.print_info(self)) self.id_number
Finally, to use this, call:
print(john.get_employee_info())
CodePudding user response:
Both your print_*
methods look like they should be converted to __str__
methods.
class Person:
def __init__(self, *, name, age, height, **kwargs):
super().__init__(**kwargs)
self.name = name
self.age = age
self.height = height
def __str__(self):
return f'{self.name}, age {self.age}, height {self.height} cm'
class Employee(Person):
def __init__(self, *, id_number, **kwargs):
super().__init__(**kwargs)
self.id_number = id_number
def __str__(self):
return super().__str__() self.id_number
john = Employee(name="John", age="20", height="182", id_number="2230")
print(john)
Try to push I/O "up" as far as possible in your code. If your method can return a string for someone else to print rather than printing it itself, do it.