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()
Related
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 :)
Is there a way I could implement user input to create a new entry in this class I defined?
class Pulsar:
'Collective base of all Pulsars'
pulsarCount = 0
def __init__(self, name, distance):
self.name = name
self.distance = distance
Pulsar.pulsarCount += 1
def displayCount(self):
print( "Total Pulsars %d" % Pulsar.pulsarCount)
def displayPulsar(self):
print( "Name : ", self.name, ", Distance: ", self.distance)
"This creates the first object"
pulsar1 = Pulsar("B1944+17", "979 Lightyears")
"This creates the second pulsar in the class"
pulsar2 = Pulsar("J2129-5721", "1305 Lightyears")
pulsar1.displayPulsar()
pulsar2.displayPulsar()
print( "Total Pulsars %d" % Pulsar.pulsarCount)
I'm hoping for the user to be able to input their own name/distance and have it append to my current defined variables.
Depending on what you're doing with the Pulsar objects, a class may be overkill.
class Pulsar:
def __repr__(self) -> str:
return f'Pulsar({self.name!r}, {self.distance!r})'
def __init__(self, distance: str, name: str) -> None:
self.name: str = name
self.distance: str = distance
num_pulsars_input = int(input('How many pulsars do you wish to create: '))
pulsar_list = []
for _ in range(num_pulsars_input):
curr_p_name = input('Enter pulsar name: ')
curr_p_dist = input('Enter pulsar distance: ')
curr_p = Pulsar(curr_p_name, curr_p_dist)
pulsar_list.append(curr_p)
print(pulsar_list)
class Pulsar:
'Collective base of all Pulsars'
pulsarCount = 0
def __init__(self, name, distance):
self.name = name
self.distance = distance
Pulsar.pulsarCount += 1
def displayCount(self):
print( "Total Pulsars %d" % Pulsar.pulsarCount)
def displayPulsar(self):
print( "Name : ", self.name, ", Distance: ", self.distance)
"This creates the first object"
pulsar1 = Pulsar("B1944+17", "979 Lightyears")
"This creates the second pulsar in the class"
pulsar2 = Pulsar("J2129-5721", "1305 Lightyears")
pulsar1.displayPulsar()
pulsar2.displayPulsar()
print( "Total Pulsars %d" % Pulsar.pulsarCount)
# New code
users_name = input('Your name: ')
distance = input('The distance: ')
pulsar1.name = users_name
pulsar1.distance = distance
# Then you can wrap this in a function if you want
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)
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()
i`m trying to learn classes, and something is holding em back, i get
"NameError: global name 'self' is not defined"
the same happens to each class field. can you help me find what am i doing wrong thank you
Code:
class Assignment:
def __init__(self, name, discription, deadline, grade, studentID):
self.name = name
self.studentID = studentID
self.description = discription
self.deadline = deadline
self.grade = grade
def __str__(self):
return "studentID:" + self.studentID + "assignment name:" + self.name +" description:" + self.description + " deadline:" + self.deadline + " grade:" + self.grade
def validation(self):
errors= []
if self.studendID == "":
errors.append("No existing student ID.")
if self.description == "":
errors.append("No existing description.")
if self.deadline == "":
errors.append("No existing deadline.")
if self.deadline == "":
errors.append("No existing deadline.")
return errors
#staticmethod
def dummyAssignments():
ret = []
for studentID in range(100, 121):
print "sda"
a = Assignment(self, name, discription, deadline, grade, studentID)
ret.append(a)
return ret
def testAssigment():
a = Assignment("","","","","")
print a
testAssigment()
print Assignment.dummyAssignments()
The problem is here:
a = Assignment(self, name, discription, deadline, grade, studentID)
This is in a #staticmethod, so self isn't defined.
Indeed, none of those values are defined, come to think of it -- except studentID.
You don't need to pass self when instantiating your class.
Assignment(self, name, discription, deadline, grade, studentID)
should be
Assignment(name, discription, deadline, grade, studentID)
The error is letting you know you are trying to use a var self that is not defined in either local or global scope.
The dummyAssignments static method only has studentIDs but not any of the other fields.
Try giving default values to each of the fields:
class Assignment:
def __init__(self, name='', discription='', deadline='', grade='', studentID =''):
self.name = name
self.studentID = studentID
self.description = discription
self.deadline = deadline
self.grade = grade
def __str__(self):
return "studentID:" + self.studentID + "assignment name:" + self.name +" description:" + self.description + " deadline:" + self.deadline + " grade:" + self.grade
def validation(self):
errors= []
if self.studendID == "":
errors.append("No existing student ID.")
if self.description == "":
errors.append("No existing description.")
if self.deadline == "":
errors.append("No existing deadline.")
if self.deadline == "":
errors.append("No existing deadline.")
return errors
#staticmethod
def dummyAssignments():
ret = []
for studentID in range(100, 121):
print "sda"
a = Assignment(studentID=studentID)
ret.append(a)
return ret
def testAssigment():
a = Assignment("","","","","")
print a
testAssigment()
print Assignment.dummyAssignments()
in your class decleration:
class Assignment:
change it to
class Assignment():
or
class Assignment(object):