Am I inheriting and inserting data into the classes wrong?
class Car:
def __init__(self, make, model, year):
self.make = "Honda"
self.model = "Minivan"
self.year = "2010"
class Entry(Car):
def __init__(self, make, model, year, driver, number):
super().__init__(make, model, year)
self.driver = "Mike Drosser"
self.number = 9
def printEntry(self):
print("The make is: " self.make)
print("The model is: " self.model)
print("The year is: " self.year)
print("The driver is: " self.driver)
self.number = str(self.number)
print("The number is: " self.number)
x = Entry()
x.printEntry()
Do I have to submit the Car
class data separately?
CodePudding user response:
there are 2 problem with your code:
the arguments in the constructor are all required, therefore when doing
Entry()
will fail because no arguments were provided.you don't do anything with the provided values to the constructor and instead store specific values in your instance attribute.
Beside that, everything else look fine.
A simple fix is
class Car:
def __init__(self, make, model, year):
self.make = make #we store the provided value
self.model = model
self.year = year
class Entry(Car):
def __init__(self, make, model, year, driver, number):
super().__init__(make, model, year)
self.driver = driver
self.number = number
def printEntry(self):
print("The make is: " self.make)
print("The model is: " self.model)
print("The year is: " self.year)
print("The driver is: " self.driver)
self.number = str(self.number)
print("The number is: " self.number)
x = Entry("Honda", "Minivan", "2010", "Mike Drosser", 9) #this is how a proper call of this class would look like
x.printEntry()
There are other thing that can also be changed, like your prints, the print function can take any number of arguments, so this print("The number is: " self.number)
can be change to print("The number is:", self.number)
this way you don't need to explicitly transform it to a string first in case of numbers or any non-string for that matter.
But in order to be more pythonic, change the printEntry method to the __str__
special method, that way you can call print in it
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def __str__(self):
#this method should return a string representation of this class,
#for this we use f-string to format the different attributes
return f"The make is: {self.make}\nThe model is: {self.model}\nThe year is: {self.year}"
class Entry(Car):
def __init__(self, make, model, year, driver, number):
super().__init__(make, model, year)
self.driver = driver
self.number = number
def __str__(self):
#here we make use of inheritances to split job
#by letting the Car class handle the part it
#know about and this subclass will add to it
#with the part exclusive to it
return super().__str__() f"\nThe driver is: {self.driver}\nThe number is: {self.number}"
x = Entry("Honda", "Minivan", "2010", "Mike Drosser", 9)
print(x)