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"
Related
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()
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}")
So for my last assingment in my python course at uni, I have to write a program consisting of three objects, two of which inherit. I keep running into a snag especially with regards to the last two objects. Here is my code:
class Course:
def __init__(self,title="",ID=0):
self._ID = ID
self._title = title
def getID(self):
return self._ID
def getTitle(self):
return self._title
def setTitle(self,title):
self._title = title
def setID(self,ID):
self._ID = ID
def __repr__(self):
return "Title: " + self._title + "ID: " + str(self._ID)
class OfferedCourse(Course):
def __init__(self,title="",ID=0,enrollment=[]):
super().__init__(title,ID)
self._enrollment = len(enrollment)
def getEnrollment(self):
return self._enrollment
def addStudent(self,stu):
if stu in enrollment:
print("Student is already enrolled.")
else:
enrollment.append(stu)
def dropStudent(self,stu):
if stu in enrollment:
def __repr__(self):
super().__repr__() + "Enrollment: " + str(self._enrollment)
class StudentCourse(Course):
def __init__(self,grade,ID=0,title=""):
super().__init__(title,ID)
self._grade = grade
def getGrade(self):
return self._grade
def setGrade(self,grade):
self._grade = grade
def __repr__(self):
super().__repr__() + "Grade: " + str(self._grade)
def main():
#Set primary course
lego=Course("Lego Design",32013)
#display course
print(lego)
#Set OfferedCourse
bonk=OfferedCourse("Matoran History",82932,["Josh","Rick","Greg","Chris"])
#Display OfferedCourse
print(bonk)
#Set StudentCourse
lp=StudentCourse("History of Nu-Metal",57859,82)
#display Student Course
print(lp)
At around line 60 I recieve the error:
TypeError: str returned non-string (type NoneType)
I'm pretty lost as to what is going on.
Your __repr__s don't explicitly return anything. You build up a string, then throw it away, causing None to be implicitly returned instead.
Just add a return:
def __repr__(self):
return super().__repr__() + "Grade: " + str(self._grade)
Adjustments to the source code of the original question:
add missing statement at def dropStudent(self,stu):
add missing return expression for def __repr__(self):
adjust signature of StudentCourse(Course) init to def __init__(self,title,ID,grade): to be in line with parent classes and process given statement StudentCourse("History of Nu-Metal",57859,82) as expected
add missing indentions for def main():
class Course:
def __init__(self,title="",ID=0):
self._ID = ID
self._title = title
def getID(self):
return self._ID
def getTitle(self):
return self._title
def setTitle(self,title):
self._title = title
def setID(self,ID):
self._ID = ID
def __repr__(self):
return "Title: " + self._title + "ID: " + str(self._ID)
class OfferedCourse(Course):
def __init__(self,title="",ID=0,enrollment=[]):
super().__init__(title,ID)
self._enrollment = len(enrollment)
def getEnrollment(self):
return self._enrollment
def addStudent(self,stu):
if stu in enrollment:
print("Student is already enrolled.")
else:
enrollment.append(stu)
def dropStudent(self,stu):
if stu in enrollment:
print("#todo Something is missing here...")
def __repr__(self):
return super().__repr__() + "Enrollment: " + str(self._enrollment)
class StudentCourse(Course):
def __init__(self,title,ID,grade):
super().__init__(title,ID)
self._grade = grade
def getGrade(self):
return self._grade
def setGrade(self,grade):
self._grade = grade
def __repr__(self):
return super().__repr__() + "Grade: " + str(self._grade)
def main():
#Set primary course
lego=Course("Lego Design",32013)
#display course
print(lego)
#Set OfferedCourse
bonk=OfferedCourse("Matoran History",82932,["Josh","Rick","Greg","Chris"])
#Display OfferedCourse
print(bonk)
#Set StudentCourse
lp=StudentCourse("History of Nu-Metal",57859,82)
#display Student Course
print(lp)
main()
class fase1():
def __init__ (self, num, date, desc)
self.num = num
self.date = date
self.desc = desc
class fase2(fase1):
def __init__(self, ele):
self.ele = [ele,[]]
def __str__(self):
return self.ele
def addfase2(self, num, date, desc):
newfase = fase1()
self.ele[1].append(newfase)
namefase2 = "FASE"
cload = fase2
cload.ele = namefase2
cload.addfase2(10,"date","Desc")
when print ...
['FASE',[<__main__.fase1 instance at 0x01C2BEB8>]]
can anyone help me please?
you have an array containing your fase1 object, which isn't initialized in your addfase2 method (as you'd probably want)
def addfase2(self, num, date, desc):
newfase = fase1(num, date, desc)
also if you add a __str__ method to fase1, you won't see anymore the object repr
def __str__(self):
return self.desc + ' ' + self.num + ' ' + self.date
or something like that
I'm working on getting better with OOP in Python and I've run into some real hackishness in one program I'm writing. It works, but it's a mess.
Below is a short test example to illustrate. It creates cars of either 0, 2, or 4 windows into a list, and then compares the first element with the rest of the list.
The 3rd method of the first class shows what I'm worried about. I just want to be able to refer to whatever container that particular object is in without having to call it from the parameters each time. It isn't even that bad in this example, but what I'm working on has it in so many places that it's starting to get confusing.
import random
class Car:
def __init__ (self, company, doors, id):
self.company = company
self.doors = doors
self.id = id
def printDoors(self, id):
print 'Car ' + `self.id` + ' has ' + `self.doors` + ' doors.'
def findSameDoors(self, id):
# these next lines are the ones that really bother me
companyAbstract = self.company + 's'
for i in eval(companyAbstract):
if self.id != i.id and self.doors == i.doors:
print 'Car ' + `i.id` + ' does too!'
class Company:
def __init__ (self, types):
self.types = types
def typesToNum(self):
result = []
for i in self.types:
if i == 'sedan':
result.append(4)
elif i == 'convertible':
result.append(2)
else:
result.append(0)
return result
porsche = Company(['sedan', 'convertible'])
honda = Company(['sedan', 'convertible', 'motorcycle'])
porsches = []
for i in range(10):
porsches.append(Car('porsche', random.choice(porsche.typesToNum()), i))
hondas = []
for i in range(10):
hondas.append(Car('honda', random.choice(honda.typesToNum()), i))
porsches[0].printDoors(0)
porsches[0].findSameDoors(0)
Just in case it matters, Python 2.4.3 on RHEL. Thanks!
If I'm understanding your question right, you want to attach the list of cars to the company object:
import random
class Car:
def __init__ (self, company, doors, id):
self.company = company
self.doors = doors
self.id = id
def printDoors(self, id):
print 'Car ' + `self.id` + ' has ' + `self.doors` + ' doors.'
def findSameDoors(self, id):
for i in self.company.cars:
if self.id != i.id and self.doors == i.doors:
print 'Car ' + `i.id` + ' does too!'
class Company:
def __init__ (self, types):
self.types = types
self.cars = []
def typesToNum(self):
result = []
for i in self.types:
if i == 'sedan':
result.append(4)
elif i == 'convertible':
result.append(2)
else:
result.append(0)
return result
porsche = Company(['sedan', 'convertible'])
honda = Company(['sedan', 'convertible', 'motorcycle'])
for i in range(10):
porsche.cars.append(Car(porsche, random.choice(porsche.typesToNum()), i))
for i in range(10):
honda.cars.append(Car(honda, random.choice(honda.typesToNum()), i))
porsche.cars[0].printDoors(0)
porsche.cars[0].findSameDoors(0)
There's more cleanup that could be done to it, but I think that should solve your immediate concern.