I have following code below.
class NameParser:
def __init__(self):
self.getName
def getName(self, name):
splitName = name.split(' ')
surname = splitName.pop()
for i in range(len(splitName)):
print('Name: %s' % splitName[i])
return('Surname: %s' % surname)
np = NameParser()
print(np.getName("ali opcode goren"))
# output: name: ali, name: opcode, surname: goren
How do i return two values? Like following code:
for i in range(len(splitName)):
return('Name: %s' % splitName[i])
return('Surname: %s' % surname)
# output: name ali: (error) i want all values name, name, surname
I want all values but just one output. How can I solve this problem?
Split: Split name by space and then do list comprehension again to remove the empty string from the list.
POP: get last item from the list by pop() method and assign it to surname variable.
Exception Handling: Do exception handling during pop process. If the input is empty then this will raise an IndexError exception.
string concatenate: Iterate every Item from the list by for loop and assign the value to user_name variable.
Concatenate surname in string again.
Display result.
Demo:
class NameParser:
def __init__(self):
pass
def getName(self, name):
#- Spit name and again check for empty strings.
splitName = [i.strip() for i in name.split(' ') if i.strip()]
#- Get Surname.
try:
surname = splitName.pop()
except IndexError:
print "Exception Name for processing in empty."
return ""
user_name = ""
for i in splitName:
user_name = "%s Name: %s,"%(user_name, i)
user_name = user_name.strip()
user_name = "%s Surname: %s"%(user_name, surname)
return user_name
np = NameParser()
user_name = np.getName("ali opcode goren abc")
print "user_name:", user_name
Output:
user_name: Name: ali, Name: opcode, Name: goren, Surname: abc
Try this:
class NameParser:
def __init__(self):
self.getName
def getName(self, name):
listy = [] # where the needed output is put in
splitName = name.split(' ')
for i in range(len(splitName)):
if i==(len(splitName)-1):#when the last word is reach
listy.append('Surname: '+ splitName[i])
else:
listy.append('Name: '+ splitName[i])
return listy
nr = NameParser()
print(nr.getName("ali opcode goren"))
# output: name: ali, name: opcode, surname: goren
whithout loop:
class NameParser:
def __init__(self):
self.getName
def getName(self, name):
listy = [] # where the needed output is put in
splitName = name.split(" ")
listy ="Name",splitName[0],"Name",splitName[1],"Surname",splitName[2]
return listy
nr = NameParser()
print(nr.getName("ali opcode goren"))
# output: name: ali, name: opcode, surname: goren
Try to use yield
class NameParser:
def __init__(self):
self.getName
def getName(self, name):
splitName = name.split(' ')
surname = splitName.pop()
for i in range(len(splitName)):
yield ('Name: %s' % splitName[i])
yield ('Surname: %s' % surname)
np = NameParser()
for i in (np.getName("ali opcode goren")):
print i
you can just do this:
def getName(self, name):
return name.split(' ')
It will return a tuple
def get_name(name):
return name.split(' ')
>>> get_name("First Middle Last")
['First', 'Middle', 'Last']
or you can try
class test():
map = {}
for i in range(10):
map[f'{i}'] = i
return map
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 :)
I have a class (Student) with different attributes, such as studentId, address, and courses. My str method for the class returns all the information that the user put in. However, for the attributes that are lists, such as courses, the location of the information is printed out instead of the actual information. Here is the code (sorry it's a little long, there's a bunch of classes):
class Person:
__name = None
__age = None
__address = None
def __init__(self, name, age=0, address=None):
self.set_name(name)
self.set_age(age)
self.set_address(address)
def __str__(self):
return 'Name: ' + self.__name + '\n' + \
'Age: ' + str(self.__age) + '\n' + \
'Address: ' + str(self.__address)
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_age(self, age):
self.__age = age
def get_age(self):
return self.__age
def set_address(self, address):
self.__address = address
def get_address(self):
return self.__address
class Student(Person):
def __init__(self, name, studentID= None, age= 0, address= None):
super(Student, self).__init__(name, age, address)
self.set_studentID(studentID)
self.__courses =[]
def __str__(self):
result = Person.__str__(self)
result += '\nStudent ID:' + self.get_studentID()
for item in self.__courses:
result += '\n ' + str(item)
return result
def set_studentID(self, studentID):
if isinstance(studentID, str) and len(studentID.strip()) > 0:
self.__studentID = studentID.strip()
else:
self.__studentID = 'NA'
def get_studentID(self):
return self.__studentID
def add_course(self, course):
print('in add_course')
self.__courses.append(course)
def get_courses(self):
for i in range(len(self.__courses)):
return self.__courses[i]
class Course:
__courseName = None
__dept = None
__credits = None
def __init__(self, courseName, dept= 'GE', credits= None):
self.set_courseName(courseName)
self.set_dept(dept)
self.set_credits(credits)
def __str__(self):
return self.get_courseName() + '/' + self.get_dept() + '/' + str(self.get_credits())
def set_courseName(self, courseName):
if isinstance(courseName, str) and len(courseName.strip()) > 0:
self.__courseName = courseName.strip()
else:
print('ERROR: Name must be a non-empty string')
raise TypeError('Name must be a non-empty string')
def get_courseName(self):
return self.__courseName
def set_dept(self, dept):
if isinstance(dept, str) and len(dept.strip()) > 0:
self.__dept = dept.strip()
else:
self.__dept = "GE"
def get_dept(self):
return self.__dept
def set_credits(self, credits):
if isinstance(credits, int) and credits > 0:
self.__credits = credits
else:
self.__credits = 3
def get_credits(self):
return self.__credits
students = []
def recordStudentEntry():
name = input('What is your name? ')
age = input('How old are you? ')
studentID= input('What is your student ID? ')
address = input('What is your address? ')
s1 = Student(name, studentID, int(age), address)
students.append(s1)
s1.add_course(recordCourseEntry())
print('\ndisplaying students...')
displayStudents()
print()
def recordCourseEntry():
courses = []
for i in range(2):
courseName = input('What is the name of one course you are taking? ')
dept = input('What department is your course in? ')
credits = input('How many credits is this course? ')
c1 = Course(courseName, dept, credits)
print(c1)
courses.append(c1)
displayCourses(courses)
return courses
def displayCourses(courses):
print('\ndisplaying courses of student... ')
for c in range(len(courses)):
print(courses[c])
def displayStudents():
for s in range(len(students)):
print()
print(students[s])
recordStudentEntry()
This is how the code above prints out the 'displaying students...' part:
displaying students...
Name: sam
Age: 33
Address: 123 st
Student ID:123abc
[<__main__.Course object at 0x000002BE36E0F7F0>, <__main__.Course object at
0x000002BE36E0F040>]
I know that it is printing out the location because I need to index into the list. However, the length of the list will be different every time. Normally if I wanted to index into a list, for example, to print a list of names, I would do:
listOfNames = ['sam', 'john', 'sara']
for i in range(len(listOfNames)):
print(listOfNames[i])
or
listOfNames = ['sam', 'john', 'sara']
for i in listOfNames:
print(i)
(not sure what if any difference there is between the 2 ways since they both print out the same way:)
sam
john
sara
How can I write something like the indexing into a list technique shown here in my str method for my class so that it prints the information and not the location?
It would be good to keep to the standard conventions for Python, such as naming
private attributes for objects with single underscores, not double underscores.
The latter are reserved for Python "internal" attributes and methods.
Also, it is convention to use object attributes for objects with get/set methods,
not class attributes. This will make it easier to inspect your objects, while
still maintaining data hiding. Example:
class Course:
def __init__(self, courseName, dept= 'GE', credits= None):
self._courseName = None
self._dept = None
self._credits = None
self.set_courseName(courseName)
...
Your question about why the courses don't print out the way you expected
is rooted in a programming error with the way you programmed the recording
of courses. In recordCourseEntry(), you record two courses and put them
in a list. However, you pass that to your Student object using a method
intended for one course at a time. My suggested fix would be:
...
# s1.add_course(recordCourseEntry())
courses = recordCourseEntry()
for course in courses:
s1.add_course(course)
...
This will probably be enough to get you going. An example output I got was:
Name: Virtual Scooter
Age: 33
Address: 101 University St.
Student ID:2021
ff/GE/3
gg/GE/3
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)
I have a list of objects. I would like to check some string if that string exists as a field value any object in the list. for example,
class Ani:
name = ''
def __init__(self, name):
self.name = name
def getName(self):
return self.name
animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')
a = [animal1, animal2, animal3,animal4,animal5]
my problem to write a code in order to see if there is an object with given name. for example "chip".
You can iterate over the array of objects, and check with each object's getName function.
class Ani:
name = ''
def __init__(self, name):
self.name = name
def getName(self):
return self.name
animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')
animals = [animal1, animal2, animal3,animal4,animal5]
searched_animal = 'rex'
for animal in animals:
if animal.getName() == searched_animal:
print('Found')
break
You can use any plus a comprehension:
any(animal.getName() == "chip" for animal in animals)
Iterating a list containing anything is quite simple really. Like so:
animal_to_find = "someAnimal"
for animal in animals:
if animal.getName() == animal_to_find:
print("Found a match for: " + animal)
You can use the getName method present in Ani class for this program
class Ani:
name = ''
def __init__(self, name):
self.name = name
def getName(self):
return self.name
animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')
animals = [animal1, animal2, animal3,animal4,animal5]
key = 'chip'
flag=0
for animal in animals:
if animal.getName() == key:
print('Found')
flag=1
break
if flag==0:
print("Not Found")