class and defining __str__ - python

This is the exercise:
Write the special method __str__() for CarRecord.
Sample output with input: 2009 'ABC321'
Year: 2009, VIN: ABC321
The following code is what I have came up with, but I'm receiving an error:
TYPEERROR: __str__ returned non-string
I can't figure out where I went wrong.
class CarRecord:
def __init__(self):
self.year_made = 0
self.car_vin = ''
def __str__(self):
return "Year:", (my_car.year_made), "VIN:", (my_car.car_vin)
my_car = CarRecord()
my_car.year_made = int(input())
my_car.car_vin = input()
print(my_car)

You're returning a tuple using all those commas. You should also be using self, rather than my_car, while inside the class. Try like this:
def __str__(self):
return f"Year: {self.year_made}, VIN: {self.car_vin}"
The f before the string tells Python to replace any code in braces inside the string with the result of that code.

class Car:
def __init__(self):
self.model_year = 0
self.purchase_price = 0
self.current_value = 0
def print_info():
print('Car Info') # It specifies a print_info class method but doesnt actually need to print anything useful.
def calc_current_value(self, current_year):
depreciation_rate = 0.15
car_age = current_year - self.model_year
self.current_value = round(self.purchase_price * (1 - depreciation_rate) ** car_age)
def print_info(self):
print("Car's information:")
print(" Model year:", self.model_year)
print(" Purchase price:", self.purchase_price)
print(" Current value:", self.current_value)
if __name__ == "__main__":
year = int(input())
price = int(input())
current_year = int(input())
my_car = Car()
my_car.model_year = year
my_car.purchase_price = price
my_car.calc_current_value(current_year)
my_car.print_info()

def __str__(self):
return "Year: {}, VIN: {}".format(self.year_made, self.car_vin)
The trick here is that you pull values from the top of the class as they are set later in the code.

This answer works for grading
def __str__(self):
return f"Year: {}, VIN: {}".format(self.year_made, self.car_vin)`
This is easier to understand
def __str__(self):
f"Year: {self.year_made}, VIN: {self.car_vin}")

Related

How to get model number?

The first class contains the car details and in the second Service class using the get_car_by_year() method. I need to return car based on the date of manufacturing using get_* function of the first class, but I am getting None no matter which year I enter.
Code:
class Car:
def __init__(self,model,year,registration_number):
self.__model=model
self.__year=year
self.__registration_number=registration_number
def get_model(self):
return self.__model
def get_year(self):
return self.__year
def get_registration_number(self):
return self.__registration_number
def __str__(self):
return(self.__model+" "+self.__registration_number+" "+(str)(self.__year))
class Service:
def __init__(self,car_list):
self.__car_list = car_list
def get_car_by_year(self,year):
result_list = []
for car in self.__car_list:
if(car.get_year() == year):
result_list.append(car.get_model())
if(len(result_list) == 0):
return None
return result_list
car1=Car("WagonR",2010,"KA09 3056")
car2=Car("Beat", 2011, "MH10 6776")
car3=Car("Ritz", 2013,"KA12 9098")
car4=Car("Polo",2013,"GJ01 7854")
car5=Car("Amaze",2014,"KL07 4332")
car_list=[car1, car2, car3, car4,car5]
a1 = Service(car_list)
print(a1.get_car_by_year(2013))
Your return statements are inside loop which will always return null, because the first car in your car list is WagonR which is 2010. If you would call your current function get_car_by_year with a 2010 year you will get your desired output.
Placing both return statements outside for loop will do the trick
def get_car_by_year(self,year):
result_list = []
for car in self.__car_list:
if(car.get_year() == year):
result_list.append(car.get_model())
if (len(result_list) == 0):
return None
return result_list

The print(abhishek.increment) in the last line is not giving the answer I want, can someone tell why?

class Employee:
company = 'Google'
def __init__(self, name, salaryInput, salIncrement):
self.name = name
self.salaryInput = salaryInput
self.salIncrement = salIncrement
def salary(self):
print('Base salary of {} is ${}'.format(self.name, self.salary))
def increment(self):
print('Increment in salary = ${}'.format(self.salIncrement))
#property
def salaryAfterIncrement(self):
return self.salaryInput + self.salIncrement
#salaryAfterIncrement.setter
def salaryAfterIncrement(self, salaryInput):
self.increment = salaryAfterIncrement - self.salaryInput
abhishek = Employee('Abhishek', 100, 50)
print(abhishek.salaryAfterIncrement)
print(abhishek.increment)
You need to add parenthesis. And BTW, you need to use return in .increment() function. This wouldn't solve your problem but it will print a None. So try -
return 'Increment in salary = ${}'.format(self.salIncrement)
Then use print -
print(abhishek.increment())
Or if you do not want to use return then call the function without print statement -
print('Increment in salary = ${}'.format(self.salIncrement))
Then call the function -
abhishek.increment()

AttributeError: 'str' object has no attribute 'get_grade'

hello was following alone in a tutorial and the code that he has is the exact same that i have here but mine doesn't seem to work. when he ran the code his worked completely fine and i am running into errors. code it be that i need to add the parent to the subject such as subject(person)? or is something just wrong. The number get_average function should just return the number but it is having problems with that. appreciate the help
class Person():
def __init__(self, first, last, grade):
self.first = first
self.last = last
self.grade = grade
def get_grade(self):
return self.grade
class Subject():
def __init__(self, subject, number_students):
self.subject = subject
self.number_students = number_students
self.students = []
def add(self, name):
if len(self.students) < self.number_students:
self.students.append(name)
return True
return False
def average(self):
number = 0
for i in self.students:
number += i.get_grade()
return number
p1 = Person("dustin", "white", 83)
subs = Subject("science", 10)
subs.add(p1.first)
print(subs.students)
print(subs.average())
The error arises because you run subs.add(p1.first), which is a type str. p1.first does not have the method get_grade. What you want to run is: subs.add(p1) (the object which will have get_grade). Also, you can remove the redundant parentheses when defining the classes. You can write class Subject(): as class Subject:.
You can then change you add code to:
def add(self, student):
if len(self.students) < self.number_students:
self.students.append(student.first) # changed here
return True
return False

How to get rid of eval in subclass appending to superclass instance list?

I am using eval to run a generated string to append the newly created EggOrder instance to the list of the correct instance of the DailyOrders class. The day provided by EggOrder is used to used to append to the correct instance. This relies on eval and the variable name of the DailyOrders instance and so it would be great to get this removed. I know there must be a better way.
class DailyOrders:
PRICE_PER_DOZEN = 6.5
def __init__(self, day):
self.orders = []
self.day = day
def total_eggs(self):
total_eggs = 0
for order in self.orders:
total_eggs += order.eggs
return total_eggs
def show_report(self):
if self.total_eggs() < 0:
print("No Orders")
else:
print(f"Summary:\nTotal Eggs Ordered: {self.total_eggs()}")
print(f"Average Eggs Per Customer: {self.total_eggs() / len(self.orders):.0f}\n*********")
class EggOrder():
def __init__(self, eggs=0, name="", day=""):
if not name:
self.new_order()
else:
self.name = name
self.eggs = eggs
self.day = day
eval(f"{self.day.lower()}.orders.append(self)")
def new_order(self):
self.name = string_checker("Name: ")
self.eggs = num_checker("Number of Eggs: ")
self.day = string_checker("Date: ")
def get_dozens(self):
if self.eggs % 12 != 0:
dozens = int(math.ceil(self.eggs / 12))
else:
dozens = self.eggs / 12
return dozens
def show_order(self):
print(f"{self.name} ordered {self.eggs} eggs. The price is ${self.get_dozens() * DailyOrders.PRICE_PER_DOZEN}.")
if __name__ == "__main__":
friday = DailyOrders("Friday")
friday_order = EggOrder(12, "Someone", "Friday")
friday_order.show_order()
friday.show_report()
saturday = DailyOrders("Saturday")
saturday_order = EggOrder(19, "Something", "Saturday")
saturday_order = EggOrder(27, "Alex Stiles", "Saturday")
saturday.show_report()
DailyOrders isn't actually a superclass (it was in a earlier version), it acts like one and I suspect the answer might have some inheritance.

How do I sent up a print method for my class?

Me very very new programmer, I'm new to classes and not sure how to set up a print method for this class. How do I go about setting up a print method for my class here? Thanks for anything!
class travelItem :
def __init__(self, itemID, itemName, itemCount) :
self.id = itemID
self.name = itemName
self.itemCount = itemCount
self.transactions = []
def getID(self) :
return(self, id)
def getName(self) :
return(self.name)
def setName(self, newName) :
self.name = newName
def getAvailableStart(self):
return(self.AvailableStart)
def appendTransaction(self, num) :
self.transactions.append(num)
def getTransactions(self) :
return(self.transactions)
def getReservations(self) :
Additions = 0
for num in self.transactions :
if (num > 0) :
Additions = Additions + num
return(Additions)
def getCancellations(self) :
Subtractions = 0
for num in self.transactions :
if (num < 0) :
Subtractions = Subtractions + num
return(Subtractions)
def getAvailableEnd(self) :
total = self.AvailableStart
for num in self.transactions :
total = total + num
return(total)
Remember that a method is called on an instance of a class, so if you mean to create a true method that just prints a class you can write something like
class Foo(object):
def print_me(self):
print(self)
foo_instance= Foo()
foo_instance.print_me()
But it sounds like you want to customize the output of print(). That is what the built in method __str__ is for, so try this.
class Foo(object):
def __str__(self):
# remember to coerce everything returned to a string please!
return str(self.some_attribute_of_this_foo_instance)
a good example from your code might be
...
def __str__(self):
return self.getName + ' with id number: ' + str(self.getId) + 'has ' + str(self.getTransactions) + ' transactions'
You must use a __str__ special method:
class travelItem:
...
def __str__(self):
return "a string that describe the data I want printed when print(instance of class) is called"

Categories

Resources