How to remove an object from list by a value - python-3.x

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

Related

how to access to data from a class which is stored in another class in python?

This is my code. I got a problem when i want to print the information inside the class 'pokemon'
class trainer(object):
def __init__(self, name, pokemons = [], money = 0):
self.name = name
self.pokemons = pokemons
self.money = money
this is my first class which has every pokemon per trainer
class pokemon(object):
def __init__(self, name, attribute, attacks = {}, health = '==========='):
self.name = name
self.attribute = attribute
self.health = health
self.attacks = attacks
The other class where I take the pokemon to import to the other class
class fight():
def __init__(self, fighter1, fighter2):
self.fighter1 = fighter1
self.fighter2 = fighter2
def fighting(self):
if len(Trainer1.pokemons) >= 1 and len(Trainer2.pokemons) >= 1:
print('{} wanna fight against {}'.format(Trainer1.name, Trainer2.name))
keepgoing = True
print('{} got this Pokemons: '.format(Trainer1.name))
i = 0
for i in Trainer1.pokemons:
print(i)
#while (keepgoing):
else:
print('You gotta have pokemons to fight')
return False
I thought that creating a class named fight for getting in battle would be the most wise idea but I'd like to know another method to do it
Pokemon1 = pokemon('Charizard', 'Fire', attacks={'1':'ball fire', '2':'cut', '3':'fire blast', '4':'mega kick'})
Pokemon2 = pokemon('Charmander', 'fire', attacks={'1':'blast', '2':'scratch', '3':'heat', '4':'tear'})
Trainer1 = trainer('Santiago', pokemons=[Pokemon1, Pokemon2])
Pokemon3 = pokemon('Charizard', 'Fire', attacks={'1':'ball fire', '2':'cut', '3':'fire blast', '4':'mega kick'})
Pokemon4 = pokemon('Charmander', 'fire', attacks={'1':'blast', '2':'scratch', '3':'heat', '4':'tear'})
Trainer2 = trainer('Alejandra', pokemons=[Pokemon3, Pokemon4])
Okay my problem is in the class fight. when i want to print the names of the pokemons i get the following message:
Santiago got this Pokemons:
<__main__.pokemon object at 0x000002AAD9B64D00>
<__main__.pokemon object at 0x000002AAD9B92DF0>
i know that the pokemon class has various instances, but how can i access to them?
To make your life easier, I recommend that you implement the __str__ dunder method on pokemon. This will resolve the issue that you are seeing right now, and make future prints of pokemon much easier.
That would look something like this:
class pokemon(object):
def __init__(self, name, attribute, attacks = {}, health = '==========='):
self.name = name
self.attribute = attribute
self.health = health
self.attacks = attacks
def __str__(self):
return "Pokemon: %s (Health: %11s)" % (self.name, self.health)
When you print the 'Charmander' pokemon, it'll look something like this:
Pokemon: Charmander (Health: ===========)
Of course, you can change the return of the __str__ to return whatever you want out of the pokemon.

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

I am not able to print the value by object of the class input taken by the user

print(xyz.age) #not able to print this
class abc:
def __init__(self):
pass
#classmethod
def getinput(self):
self.name = input("enter your name")
self.age= input("enter your age")
self.gender = input("enter your gender")
self.address = input("enter your address")
print( 'your name is {} and age is {} your are {} and you live at {}'.format(self.name,self.age,self.gender,self.address))
xyz = abc.getinput()
print(xyz.age) #not able to print this
You did not instantiate your class correctly you are just calling one of its methods.
Try this...
xyz = abc()
xyz.getinput()
print('Age', xyz.age)
Two things,
1) xyz is not a instance of your class, it is just storing whatever you are returning from getinput(In your case, you are returning None).
2) For accessing variables of abc class, you need to create instance like
xyz = abc(). then you can access the attributes of class through xyz instance.

Is there a way to dynamically sort variables into classes?

I have these two Classes: "Employee" - the superclass and "Salesman" - a subclasss of "Employee".
And I have eric = ('Eric', 19, 'Salesman', 1700).
Can i use a function to check if Eric is a Salesman and dynamically assign him to either the "Employee" superclass or the "Salesman" subclass?
And how should I go about writing that?
I hope, my description of the problem wasn't too confusing.
class Employee():
'''the employee superclass'''
def __init__(self, name, age, occupation, monthly_pay):
self.isemployee = True
self.name = name
self.age = age
self.occ = occupation
self.pay = monthly_pay
class Salesman(Employee):
'''the Salesman subclass'''
def __init__(self):
self.issalesman = True
After some trial and error, and rewriting, this is what I came up with:
class Employee():
'''The employee superclass'''
def __init__(self, name, age, occupation, monthly_pay):
self.name = name
self.age = age
self.occ = occupation
self.pay = monthly_pay
class Salesman(Employee):
'''The Salesman subclass'''
def issalesman(self):
self.issalesman = True
def class_assigner(person):
if person[2] == 'Salesman':
person = Salesman(person[0], person[1], person[2], person[3])
else:
person = Employee(person[0], person[1], person[2], person[3])
return person
print(class_assigner(eric).occ)
Output:
Salesman
Is this a viable method, or will i run into problems later, if I, say for example start importing employee - data from a .txt or .csv file?

getting all attributes of an object python 3

I read all questions and answers about this but none seems to help , using var from one of the answers was close but i need to use the same function with different objects. What should i change in the function so i don't have to make multiple functions for each object, i mean say i have another objects Human , Plants do i have to make a function for each one just changing the animal syntax:
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
def get_info(self) :
if __name__ == '__main__':
animal = Animal()
temp = vars(animal)
for item in temp:
print(item , ' : ' , temp[item])
Instead of hard coding the variable you should do this:
class Animal(object):
def __init__(self, legs, name, color, smell, age, kids):
self.legs = legs
self.name = name
self.color= color
self.smell= smell
self.age = age
self.kids = kids
if __name__ == '__main__':
animal = Animal(2, 'Dog', 'Spotted', 'Alot', 10, 0)
temp = vars(animal)
for item in temp:
print(item , ' : ' , temp[item])
i figured it out all i had to do was assigning user input to a variable then call it from objects like this :
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
noun = input()
def get_info(noun) :
if __name__ == '__main__':
character = Object.objects[noun]
temp = vars(character)
for item in temp:
print(item , ' : ' , temp[item])

Resources