Python printing a object - python-3.x

In the below code I need to print the contactlist object..How do I do that?
# Test.py
class ContactList(list):
def search(self, name):
'''Return all contacts that contain the search value
in their name.'''
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
class Contact:
all_contacts = ContactList()
def __init__(self, name, email):
self.name = name
self.email = email
self.all_contacts.append(self)
I have created 2 object of Contact but want to see all the elements in the all_contacts list..

How about:
print(Contact.all_contacts)
or:
for c in Contact.all_contacts:
print("Look, a contact:", c)
To control how the Contact prints, you need to define a __str__ or __repr__ method on the Contact class:
def __repr__(self):
return "<Contact: %r %r>" % (self.name, self.email)
or, however you want to represent the Contact.

Related

Implementing a python class

I am working on a personal project and I am having trouble implementing this following part.
Implementing a Menu Class.
This class will make use of MenuItem objects.
This class represents the restaurant menu which contains 4 different categories of menu item diners can order from.
This class will have a single class(or static) variable:
Menu_Item_types: a list containing 4 strings representing the 4 possible types of menu items.: Drink, appetizer, entree, dessert.
This class will use the following instance attribute:
List item
self.menuItemDrinkList: list of all drink list
self.menuItemAppetizerList: list of all appetizer list
self.menuItemEntreeList: a list of all entree list
self.menuItemDessertList: a list of all the dessert list
Below is the menuItem object
class MenuItem:
def __init__(self, name=None, types=None, price=None, description=None):
self.name = name
self.types = types
self.price = price
self.description = description
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setTypes(self, types):
self.types = types
def getTypes(self):
return self.types
def setPrice(self, price):
self.price = price
def getPrice(self):
return self.price
def setDescription(self, description):
self.description = description
def getDescription(self):
return self.description
def __str__(self):
return "{} ({}): ${}, {}".format(self.name, self.types, self.price, self.description)
If I understand you correctly you are looking for setters and getters properties. Here is the way how you do it in Python.
You can learn more about properties here:
class MenuItem:
def __init__(self, name=None, types=None, price=None, description=None):
self._name = name
self._types = types
self._price = price
self._description = description
#property
def name(self):
return self._name
#name.setter
def name(self, name):
self._name = name
#property
def types(self):
return self._types
#types.setter
def types(self, types):
self._types = types
#property
def price(self):
return self._price
#price.setter
def price(self, price):
self._price = price
#property
def description(self):
return self._description
#description.setter
def description(self, description):
self._description = description
def __str__(self):
return "{} ({}): ${}, {}".format(
self._name, self._types, self._price, self._description
)
menu_item = MenuItem("pizza", "entry", 10)
print(menu_item)
menu_item.price = 20
menu_item.description = "Delicious"
print(menu_item)
output:
pizza (entry): $10, None
pizza (entry): $20, Delicious
Please notice:
In python you don't call properties with getXxx or setXxx, you just use regular names and decoreate methods with #property and #xxx.setter
You should have #property before #setter.
Setter must start with the property name
In order to escape recursion, name your internal
attributes with _ (_name). If you will not do it you will have a
"RecursionError: maximum recursion depth exceeded in comparison"
because setter will call itself in the loop.

How to remove an object from list by a value

My problem is that I created a list of students with name and number. The task is now to remove a student by his number. My problem is that my code doesn't work.
Another problem is that it always shows the memory address instead of the value of the object.
Thanks in advance
class Student:
def __init__(self, name, number):
self.name = name
self.number = number
from .student import Student
class Course:
def __init__(self, name, code, credit, student_limit):
self.name = name
self.code = code
self.credit = credit
self.student_limit = student_limit
students = []
def add_student(self, new_student):
self.student = new_student
self.students.append(new_student)
print("Student added" +str(self.students))
def remove_student_by_number(self, student_number):
self.student_number = student_number
if student_number in self.students: self.students.remove(student_number)
print("Student removed" + str(self.students))
from .course import Course
class Department:
def __init__(self, name, code):
self.name = name
self.code = code
courses = []
def add_course(self, course):
self.course = course
self.courses.append(course)
print("Course added" +str(self.courses))
from python import *
def main():
alice = Student("Alice", 1336)
bob = Student("Bob", 1337)
math_dept = Department("Mathematics and Applied Mathematics", "MAM")
math_course = Course("Mathematics 1000", "MAM1000W", 1, 10)
math_dept.add_course(math_course)
math_course.add_student(bob)
math_course.add_student(alice)
math_course.remove_student_by_number(alice.number)
if __name__ == "__main__":
main()
self.students is a list of Student instance so it will print the instance's memory address if the method __str__ is not implemented (see here for example). You should try to print each property like student.name or student.number explicitly.
Anyway you are trying to find student_number in list of Student so of course it will never run the remove line. Instead use if student_number in [student.number for student in self.students] which is looking up the student's number list, not the student list itself. However in this case, you also want to remove the student with the student_number as the input so you may need to use a loop like this:
def remove_student_by_number(self, student_number):
for student in self.students:
if student.number == student_number:
print("Student removed" + str(student.name))
self.students.remove(student)
break

How to connect patient class with doctor class?

so I'm working on a problem I found online just to practice my python coding skills and I got stuck somewhere along the line. So I was trying to list all the patient name with the one of the class definition called print_list_of_patients. However, I don't know how to link the patient with the attribute so that I could just refer to the name based on the date of their appointment
I tried to combine each patient into tuples, dict but I still couldn't get what I'm looking for. Basically, I was trying to group the patient class so that every time I look at the appointment date, I can access their name and their sickness as well.
class Doctor:
def __init__(self, name):
self.name = name
self.list_of_patient = []
self.availability = []
def __str__(self):
return "Hi, this is Dr. {a}".format(a=self.name)
def add_patient(self, patient):
self.list_of_patient.
def remove_patient(self, patient):
for dates in self.availability:
if len(self.list_of_patient) == 0 and self.availability[dates]:
print("There is no patient left")
else:
self.list_of_patient.remove(patient.name)
def add_days(self, *dates):
self.availability.append(dates)
def remove_days(self, *date):
for num in range(len(self.availability)):
if date == self.availability:
self.availability.remove(date)
def print_list_of_patient(self, date):
print("Dr. {a} patient's list for {b}:\n".format(a=self.name, b=date))
class Patient:
def __init__(self, name, sickness, date_of_appointment):
self.name = name
self.sickness = sickness
def __str__(self):
return "Name: {a}\n Sickness: {b}\n\n".format(a=self.name, b=self.sickness)
def set_up_appointment(doctor, patient):
"""
set_up_appointment(doctor, patient, date)
doctor = variable name (unique ID)
patient = variable name (unique ID)
:return:
"""
doctor.add_patient(patient)
def cancel_an_appointment(doctor, patient):
"""
cancel_an_appointment(doctor, patient)
doctor = variable name (unique ID)
patient = variable name (unique ID)
:return:
"""
for names in range(len(doctor.number_of_patient)):
if patient.name == doctor.number_of_patient[names].name:
doctor.remove_patient()

Call the value of variable of method in another method of same class in python

I want to access father's name in the last function(enquiry()), and the name is present in the father() function. How to access value of the name variable in the father() function?
class family(object):
def __init__(self,members,surname):
self.members=members
self.surname=surname
def father(self,name,occupation):
self.name=name
self.occupation=occupation
def mother(self,name,occupation):
self.name=name
self.occupation=occupation
def children(self,numbers):
self.numbers=numbers
def enquiry(self):
print("The name of the father is "self.father(name))
family(4,'vora')
family.father('john','business')
family.enquiry()
This code corrects your syntactic errors but you should definitely take member P i's advice because this is ugly
class family(object):
def __init__(self,members,surname):
self.members=members
self.surname=surname
def father(self,name,occupation):
self.fathers_name=name
self.occupation=occupation
def mother(self,name,occupation):
self.mothers_name=name
self.occupation=occupation
def children(self,numbers):
self.numbers=numbers
def enquiry(self):
print("The name of the father is " + self.fathers_name)
f = family(4,'vora')
f.father('john','business')
f.enquiry()

How to spot my error in Python?

Write a class named Person with data attributes for a person’s name, address, and telephone number. Next, write a class named Customer that is a subclass of the Person class.
The Customer class should have a data attribute for a customer number and a Boolean data attribute indicating whether the customer wishes to be on a mailing list. Demonstrate an instance of the Customer class in a simple program.'
This is what I have for my code, but I keep getting the following error:
Traceback (most recent call last):
File "/Users/ryanraben/Desktop/person1.py", line 45, in <module>
import customer
ModuleNotFoundError: No module named 'customer'
I have been struggling with this class this semester. I found someone asking a similar question here in Stack Overflow but their code was very different than what I had (and if I copied their code I still could not get the correct results). This was a video module and I entered my code as it appeared on the instructor's screen, but obviously I didn't do it right because his code works and mine does not.
class Person:
def __init__(self, name, address, phone):
self.__name = name
self.__address = address
self.__phone = phone
def set_name (self, name):
self.__name = name
def set_address (self, address):
self.__address = address
def set_phone (self, phone):
self.__phone = phone
def get_name (self):
return self.__name
def get_address (self):
return self.__address
def get_phone (self):
return self.__phone
class Customer (Person):
def __init__(self, name, address, phone, customer_number, mailing_list):
Person.__init__(self, name, adress, phone)
self.__customer_number = customer_number
self.__mailing_list = mailing_list
def set_customer_number (self, customer_number):
self.__customer_number = customer_number
def set_mailing_list(self, mailing_list):
self.__mailing_list = mailing_list
def get_customer_number(self):
return self.__customer_number
def get_mailing_list (self):
return self.__mailing_list
import customer
name = input ('Name: ')
address = input ('Address: ')
phone = input ('Phone: ')
customer_number = input ('Customer number: ')
mail = input ('Include in mailing list? (y/n): ')
if mail.lower()=='y':
mailing_list = True
else:
mailing_list = False
my_customer = customer.Customer (name, address, phone, customer_number, mailing_list)
print ('Customer Information')
print ('-----------------------------')
print ('Name: ', my_customer.get_name())
print ('Address: ', my_customer.get_address())
print ('Phone: ', my_customer.get_phone())
print ('Customer number: ', my_customer.get_customer_number())
print ('Mailing list: ', my_customer.get_mailing_list())
This is a pretty common error:
You're attempting to import the library of customer and your IDE is simply not able to find this file.
Since you're defining the Class Customer I can't see any reason why you would need to import this non-existant library.
Consequently, I suggest you delete the line import customer.
That is unless I've misunderstood something.
remove this line(import customer) and remove customer from 'customer.Customer' while creating the object. After all of this you have error of 'adress' not defined. Find this attribute in your code and change it to address. Thats All dear.

Resources