(Python Derived Classes) Not getting the correct output - python

This is my desired output:
Name: Smith, Age: 20, ID: 9999
Here is my code so far
class PersonData:
def __init__(self):
self.last_name = ''
self.age_years = 0
def set_name(self, user_name):
self.last_name = user_name
def set_age(self, num_years):
self.age_years = num_years
# Other parts omitted
def print_all(self):
output_str = 'Name: ' + self.last_name + ', Age: ' + str(self.age_years)
return output_str
class StudentData(PersonData):
def __init__(self):
PersonData.__init__(self) # Call base class constructor
self.id_num = 0
def set_id(self, student_id):
self.id_num = student_id
def get_id(self):
return self.id_num
course_student = StudentData()
course_student = StudentData()
course_student.get_id(9999)
course_student.set_age(20)
course_student.set_name("Smith")
print('%s, ID: %s' % (course_student.print_all(), course_student.get_id()))
At the moment, it isn't running. I would really appreciate it if someone could help out. It is returning a type error for line 34, and I am not sure how to correct it. Any help would be greatly appreciated.

You're invoking the parent init wrongly there...
Here's how you're supposed to do it:
class PersonData:
def __init__(self):
self.last_name = ''
self.age_years = 0
def set_name(self, user_name):
self.last_name = user_name
def set_age(self, num_years):
self.age_years = num_years
# Other parts omitted
def print_all(self):
output_str = 'Name: ' + self.last_name + ', Age: ' + str(self.age_years)
return output_str
class StudentData(PersonData):
def __init__(self):
super().__init__() # Call base class constructor
self.id_num = 0
def set_id(self, student_id):
self.id_num = student_id
def get_id(self):
return self.id_num
course_student = StudentData()
course_student = StudentData()
course_student.set_id(9999)
course_student.set_age(20)
course_student.set_name("Smith")
print('%s, ID: %s' % (course_student.print_all(), course_student.get_id()))
I also noticed that in the execution, you were calling course_student.get_id(9999) but I think you meant course_student.set_id(9999)

Related

I'm VERY new to coding, but I'm trying to figure out why my print function is not resulting in what I'm expecting. Any idea?

I've created a class named Patient that has attributes for patient information. I'm supposed to use an accessor and mutator method for each attribute. Then I've created another file to access the class and insert patient information to print. Every time I print I don't get what I expect but I get <Assignment4Q1PatientClass2nd.Patient object at 0x000002429E038A00>.
Here's what is on my first file (File name is Assignment4Q1PatientClass2nd):
class Patient:
def __init__(self, fname, mname, lname, address, city, state, zipcode, phone, ename, ephone):
self._fname = fname #first name
self._mname = mname #middle name
self._lname = lname #last name
self._address = address #address
self._city = city #city for address
self._state = state #state for address
self._zipcode = zipcode #zipcode for address
self._phone = phone #phone number
self._ename = ename #emergency name
self._ephone = ephone #emergency phone
#add patient information
def addFirstName(self, firstname):
self._fname = self._fname + firstname
def addMiddleName(self, middlename):
self._mname = self._mname + middlename
def addLastName(self, lastname):
self._lname = self._lname + lastname
def addAddress(self, locaddress):
self._address = self._address + locaddress
def addCity(self, cityname):
self._city = self._city + cityname
def addState(self, statename):
self._state = self._state + statename
def addZipcode(self, zipcodenum):
self._zipcode = self._zipcode + zipcodenum
def addPhone(self, phonenum):
self._phone = self._phone + phonenum
def addEName(self, emergencyname):
self._ename = self._ename + emergencyname
def addEPhone(self, emergencyphone):
self._ephone = self._ephone + emergencyphone
#get/return all information of the Patient
def getPatientFirstName(self):
return "First Name:" + self._fname
def getPatientMiddleName(self):
return "Middle Name:" + self._mname
def getPatientLastName(self):
return "Last Name:" + self._lname
def getPatientAddress(self):
return "Address:" + self._address
def getPatientCity(self):
return "City:" + self._city
def getPatientState(self):
return "State:" + self._state
def getPatientZipcode(self):
return "ZIP:" + self._zipcode
def getPatientPhone(self):
return "Phone:" + self._phone
def getPatientEName(self, emergencyname):
return "Emergency Contact:" + self._ename
def getPatientEPhone(self, emergencyphone):
return "Emergency Phone:" + self._ephone
on the second file is:
from Assignment4Q1PatientClass2nd import Patient
pat = Patient("James", "Edward", "Jones", "345 Main Street", "Billings", "Montanna", 59000, "406-555-1212", "Jenny Jones", "406-555-1213")
print(pat)
What did you expect from your print statement?
The class actually don't "know" what to print. You must provide a way to represent that class as a string, so we can print that string.
In practice, we do this by adding a function called "__repr__", the representation of this class. Python automatically identifies this as a especial one, just like "__init__".
Here is a small example to you:
class Patient:
def __init__(self, name):
self._name = name
def getPatientName(self):
return self._name
def __repr__(self):
return "Hey! My name is " + self.getPatientName()
pat = Patient("Dikson")
print(pat)
# Hey! My name is Dikson
Hope it's clear :)

java.lang.IllegalStateException: 2 members with a #ValueRangeProvider annotation must not have the same id (timeslotRangeLS)

Trying to generate school timetable with lab hours.
Kindly help me to solve this error! Thanks in advance.
Here is my code!
#planning_solution
class TimeTable:
timeslot_list: list[Timeslot]
timeslot_list1: list[Timeslot]
room_list: list[Room]
lesson_list: list[Lesson]
lab_list: list[Lab]
score: HardSoftScore
def __init__(self, timeslot_list, timeslot_list1, room_list, lesson_list,lab_list,
score=None):
self.timeslot_list = timeslot_list
self.timeslot_list1 = timeslot_list1
self.room_list = room_list
self.lesson_list = lesson_list
self.lab_list = lab_list
self.score = score
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLS")
def get_timeslot_list(self):
return self.timeslot_list
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLB")
def get_timeslot_list1(self):
return self.timeslot_list1
#problem_fact_collection_property(Room)
#value_range_provider("roomRange")
def get_room_list(self):
return self.room_list
#planning_entity_collection_property(Lesson)
def get_lesson_list(self):
return self.lesson_list
#planning_entity_collection_property(Lab)
def get_lab_list(self):
return self.Lab_list
#planning_score(HardSoftScore)
def get_score(self):
return self.score
def set_score(self, score):
self.score = score
def __str__(self):
return (
f"TimeTable("
f"timeslot_list={format_list(self.timeslot_list)},\n"
f"timeslot_list1={format_list(self.timeslot_list1)},\n"
f"room_list={format_list(self.room_list)},\n"
f"lesson_list={format_list(self.lesson_list)},\n"
f"lab_list={format_list(self.lab_list)},\n"
f"score={str(self.score.toString()) if self.score is not None else 'None'}"
f")"
)
Trying to get the 2 timeslots one for lesson(1 hour) and one for lab(2 hour).Here is my #planning_solution.
I defined 2 #planning_entity for both lab & lesson with #value_range_provider.
#planning_entity
class Lab(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot1: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot1 = None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot1 = timeslot1
self.room = room
#planning_variable(Base, value_range_provider_refs=['roomRange', 'timeslotRangeLB'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLB"])
def get_timeslot1(self):
return self.timeslot1
#value_range_provider(range_id = "timeslotRangeLB", value_range_type = Timeslot)
def get_possible_timeslot_list1(self):
return self.subject.teacher.student_group.room_list
def set_timeslot1(self, new_timeslot):
self.timeslot1 = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lab("
f"id={self.id}, "
f"timeslot1={self.timeslot1}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
#planning_entity
class Lesson(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot=None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot = timeslot
self.room = room
#planning_variable(Base, value_range_provider_refs=['timeslotRangeLS', 'roomRange'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLS"])
def get_timeslot(self):
return self.timeslot
#value_range_provider(range_id = "timeslotRangeLS", value_range_type = Timeslot)
def get_possible_timeslot_list(self):
return self.subject.teacher.student_group.room_list
# return self.course.teacher.department.room_list
def set_timeslot(self, new_timeslot):
self.timeslot = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lesson("
f"id={self.id}, "
f"timeslot={self.timeslot}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
The issue is you defined #value_range_provider(range_id = "timeslotRangeLS") on both your #planning_solution and your #planning_entity. You can only have one; if you want the value range to apply to every entity, do it on the #planning_solution. If you want each planning entity to have it own value range that only applies to it, do it on the #planning_entity. If you want to combine a value range that contains common values for all entities, and a value range that is per entity, use a #value_range_provider on the #planning_solution, and a #value_range_provider on the entity, but give them different ids (ex: #value_range_provider(range_id = "timeslotRangeLSSolution") and #value_range_provider(range_id = "timeslotRangeLSEntity"), and in the #planning_variable, use both range ids in the list (ex: #planning_variable(Room, ["timeslotRangeLSSolution", "timeslotRangeLSEntity"])

TypeError: __str__ returned non-string (type NoneType)

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()

Driver Class Not Returning Values - Python

My Python Class is not returning any values from using a driver to test. Is there anything wrong? All of the files are in the same folder and other similar classes are able to run and produce values.
Class:
class Person:
#Initializer
def __init__(self, first_name='', last_name='', phone_number='', address=None, social_sec_num='', emailAddress=''):
self.setFirstName(first_name)
self.setLastName(last_name)
self.setPhoneNumber(phone_number)
self.setAddress(address)
self.setSocialSecNum(social_sec_num)
self.setEmailAddress(emailAddress)
#Mutator
def setFirstName(self, first_name):
self.__first_name = first_name
def setLastName(self, last_name):
self.__last_name = last_name
def setPhoneNumber(self, phone_number):
self.__phone_number = phone_number
def setAddress(self, address):
self.__address = address
def setSocialSecNum(self, social_sec_number):
self.__social_sec_num = social_sec_num
def setEmailAddress(self, emailAddress):
self.__emailAddress = emailAddress
#Accessor Methods
def getFirstName(self):
return self.__first_name
def getLastName(self):
return self.__last_name
def getPhoneNumber(self):
return self.__phone_number
def getAddress(self):
return self.__address
def getSocialSecNum(self):
return self.__social_sec_num
def getEmailAddress(self):
return self.__emailAddress
#String Representation
def __str__(self):
people_string = \
"First Name: %s" %self.getFirstName() + "\n" +\
"Last Name: %s" %self.getLastName() + "\n" +\
"Phone Number: %s" %self.getPhoneNumber() + "\n" +\
"Address: %s" %self.getAddress() + "\n" +\
"Social Security Number: %s" %self.getSocialSecNum() + "\n" +\
"Email Address: %s" %self.getEmailAddress()
return people_string
Driver:
from PersonHierarchy import Person
import Address
def main():
p1 = Person("Nick", "D", "215-000-0000", Address("717 Test", "Test", "Texas", 75181), "000-00-0000", "test#test.com")
print(p1)
main()

Class in python instances

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

Categories

Resources