Add a result from class object to another class in python - python

Hi everyone I am new to Python and currently, I am learning about class.
I have two classes. 1 class has a result of the student's name and address.
class Student:
def __init__(self, name, address, units = []):
self.name=name
self.addrress = address
self.units=units
Now I have another class which is School. The class can store the Students by adding from Student class, count how many students are on the list, also delete the student data.
class School:
def __init__(self):
self.school = []
def __len__(self):
length(self.school)
def admission(self, student):
self.school.append(student)
def delete_student(self, name, address):
self.name=name
self.organisation=organisation
for i in range(0,len(self.school)):
if self.name.lower() == name.lower() and self.address.lower() == address.lower():
del self.school[i]
else:
print("The student you input is not exist")
I want to put all the students that I define from class Student into school.
When I do something like this
a = Student("Batman", "Gotham", ["Science","Chemi"])
b = Student("Harry", "Hogwarts", ["Magic"])
School.admission(a)
There are error that said admission() missing 1 required positional argument: 'student'
How to figure this out? Maybe I did wrong in calling the argument. Help will be appreciated.
Thank you.
=================================================

School is the class, but you defined admission as an instance method. So you need an instance of School that you can admit students to:
school = School()
school.admission(a)

Basically admission is an instance method, so you should define your school instance, then add students:
school1 = School()
school1.admission(a)

people are saying that -
school1 = School()
school1.admission(a)
this resolves issue.
But try calling the list school from school1 and it will contain the student as class object like this
print(school1.school)
#output-
[<__main__.Student object at xyz...>]
So you should change your code like this...
def admission(self,student):
self.school.append(student.name)
after changing this part of your code as how i metioned above let's try calling list now.
a=Student('harry','hogwarts',['magic','spells'])
school1=School()
school1.admission(a)
print(school1.school)
#output-
['harry']
sorry for bad variable names.
please upvote.

Related

Define a list in class and call it and use it in a function in python

I am new to classes and objects in python and in need of help.
I need to create a student class with the attributes "Classes taken". This object should store the class number (like 001), the semester it was taken it (like “fall”), and the grade the student obtained.
I am stuck with “Class taken” attribute. I don’t understand if I have to create a list or define it some other manner.
Basically, I am unable to define a list and call it and use it in a function.
and error is
NameError: name 'self' is not defined
Thanks in advance for help :)
class Student(object):
def __init__(self, number,ClassNumber,Semester,Grade):
self.number = number
self.classTaken=[]
def register():
ClassNumber = input('Enter ClassNumber: ')
Semester = input('Enter Semester: ')
Grade = input('Enter Grade: ')
print(self.classTaken.append(Student(Semester)))
student1= Student.register(self.classTaken)
You can try this one
class Student():
def __init__(self):
self.classTaken = []
def register(self,Number,ClassNumber,Semester,Grade):
self.classTaken.extend((Number,ClassNumber,Semester,Grade))
student1 = Student()
student1.register(4,2,6,8)
print(student1.classTaken)

Printing from different class

I've searched for similar questions, and have not found anything.
Apparently because my question is pretty basic, yet I find it hard to understand.
I have a class named Student. In this class I get a name of student, and his grades then calculate his average grade. That one was easy, of course.
Here's what I've succeed so far:
class Student:
def __init__(self, name, grades_list):
self.name = name
self.grades_list = grades_list
def get_grade_avg(self):
avg = sum(self.grades_list) / len(self.grades_list)
return avg
def get_name(self):
return self.name
From the previous part I have:
john = Student("John", [100, 90 ,95])
Now I need to answer the following qeustion:
Write a class ClassRoom which has a constructor that receives a list of type Student, and saves this list to a member. The following should create a class room:
class_room = ClassRoom([John])
Implement class ClassRoom such that when calling print(class_room) on a ClassRoom type prints a list of tuples of student name and student grade average, in that order.
Calling print(class_room) should output:
[('John', 95)]
How do I do it?
I'm very new to OOP and have no idea even how to start.
Thank you!
You can do it like this:
class Student:
...
def __repr__(self):
return str((self.name, self.get_grade_avg()))
class ClassRoom:
def __init__(self, students):
self.students = students
def __str__(self):
return str(self.students)
john = Student("John", [100, 90 ,95])
mike = Student("Mike", [90, 80, 85])
c = ClassRoom([john, mike])
print(c)
# [('John', 95.0), ('Mike', 85.0)]
print(c)
When you call print on some object its __str__ method is invoked and if it is not defined __repr__ is called. By default __repr__ of some object is something like this: <__main__.Student object at 0x7f4b35a3a630>
In the above code a Student knows how to show itself, (name, avg), so you can print it if you like: print(john)
And for your ClassRoom, you just need to override __str__ to show the student list. Since every student knows how to show itself, it will do the job.
you need to add str() function to both class and student classes. str() if class should iterate over the list of students and print them on by one.

How to call a class in a function Python

I'm a complete amateur, and trying to work out how to write a function that takes a list of objects, and returns a list of the names of said objects (based on whether they pass if statement). This is the class I've written from help of tutorials:
class Student:
passmark=50
def __init__(self,name,mark):
self.name=name
self.mark=mark
def passes(self):
return self.mark > Student.passmark
So from now I'm assuming I make a list of objects, say:
students = []
Though this list is just a brand new list, which was necessary sure but how would I link it to the class? From this point I want to find out which students have failed, and return them and also where I am confused:
def failed(list):
for student in Students:
if passmark > self.mark:
return list
Is all I can muster, sorry I've just gotten to classes and calling classes is quite confusing for me. The above code doesn't reference the class at all, and I really am confused on how to do so. I've no syntax errors or anything, I think my logic is fatally flawed.
You want to take all the student from the students list. So use that in the for loop. Also, you correctly encapsulated the logic of pass/fail criteria in a method, so use that.
Here is the code I think will do want you want:
def failed(list_of_students):
failed_students = []
for student in list_of_students:
if not student.passes():
failed_students.append(student.name)
return failed_students
A more advanced way of doing it is by using list comprehension:
def failed(list_of_students):
return [student for student in list_of_students if not student.passes()]
It is more pythonic, but my be harder to understand for a beginner with a C or Java background.
You can use a list comprehension like this:
def failed(list):
return [student.name for student in students if not student.passes()]
Try this code. Using list comprehension to return results. It's a very powerful python tool.
class Student:
passmark = 50
def __init__(self, name, mark):
self.name=name
self.mark=mark
def passes(self):
return self.mark > Student.passmark
def __repr__(self):
return '{} {}'.format(self.name, self.mark)
def failed(students_list):
return [student for student in students_list if student.mark < Student.passmark]
Given a Student class like you defined:
class Student:
passmark=50
def __init__(self,name,mark):
self.name=name
self.mark=mark
def passes(self):
return self.mark > Student.passmark
You could instantiate a list of students with:
students = [Student("John", 49), Student("Mary", 75)]
It looks like you are also trying to define a function that will return a list of all the failed students; you could do something like this:
def failed(student_list):
return [x for x in student_list if not x.passes()]
mark_to_pass = 50
#Approach one
class Student:
def __init__(self, student_name, student_mark):
self.name = student_name
self.mark = student_mark
self.pass_mark = self.calculate_passing_mark(mark_to_pass)
def calculate_passing_mark(self, mark_to_pass):
if self.mark >= mark_to_pass:
return True
return False
if __name__ == '__main__':
example_student = Student("Swanson", 75)
print(example_student.pass_mark)
With this approach every time a student object is created it will tell create a field telling you that student has passed. When working with lists such as a list of student objects you need to add the student to your list. Example
students = []
students.append(example_student)
Now you can look through your student list by doing
for student in students:
print(student.pass_mark) # or do some other logic passed on who passed or failed. Or even here you dont need to create pass_mark object you can just check if student.mark > pass_mark
I'm assuming that failed isn't a member function of the class Student. The below code should work for what you are trying to do.
class Student:
passmark=50
def __init__(self,name,mark):
self.name=name
self.mark=mark
def passes(self):
return self.mark > Student.passmark
students = [Student("tom",40),Student("joe",70)]
def failed(listofStudents):
listofStudentsThatFail = []
for student in listofStudents:
if not student.passes():
listofStudentsThatFail.append(student)
return listofStudentsThatFail
for s in failed(students):
print s.name
The ouput when you run the code is:
tom

Using certain attributes of an object to make other objects in a different class

For a program that creates a timetable for a doctor(specialist) I want to use certain attributes of an object created by a different class to be used in the class that makes the timetable for the doctor.
class makePatient(object):
def __init__(self,name,room):
self.name = name
self.room = room
def getPatient(self):
print(self.name)
print(self.room)
class makeSpecialist(object):
def __init__(self,name,specialization,timetable):
self.name = name
self.specialization = specialization
self.timetable = timetable
def getSpecialist(self):
print(self.name)
print(self.specialization)
print(self.timetable)
class makeAgenda(object):
def addAgenda(self):
self.timetable.append()
#I want to append the name of the patient I have defined here.
print(self.timetable)
patient1 = makePatient("Michael","101")
specialist1 = makeSpecialist("Dr. John","Hematology",[])
What do I do now, to make sure that the name "Michael" gets added to the list [] of specialist Dr. John?
Thanks in advance, I will provide further details if necessary!
I think another approach would be better; you can put the whole makePatient object into the timetable for the specialist:
specialist1 = makeSpecialist("Dr. John", "Hematology", [patient1])
Now you can access the names and other attributes of the patients in a specialist's timetable:
for patient in specialist1.timetable:
print(patient.name)
You can also define a __repr__ method to tell Python how to display an object, rather than the current getPatient:
class makePatient(object):
# ...
def __repr__(self):
return "{0} (room {1})".format(self.name, self.room)
Now when you print the whole timetable:
>>> print(specialist1.timetable)
You get the necessary information:
[Michael (room 101)]
Note also that the classes should probably be called, simply, Patient, Specialist and Agenda; the make is implied.
Finally, you will get errors in makeAgenda.addAgenda as, without an __init__, self.timetable doesn't exist for a makeAgenda object, and an empty append() doesn't do anything anyway.
Classes are often used to represent entities and operations allowed on them, include constructing, or making, new instances of them. Therefore, your classes would be better named simplyPatient, Specialist, andAgenda. The name of the method that constructs a new instance of any class in Python is always__init__().
That said, after creating aPatientand aSpecialistyou could then add patient instances to the specialist's timetable/agenda by passing it to aSpecialistmethod specifically designed for that purpose. In other words, a Specialist "has-a" Agenda instance namedtimetableand to which patients can be added via an appropriately namedadd_to_timetable()method.
Here's what I mean -- note I've modified your code to follow PEP 8 -- Style Guide for Python Code guidelines which I also suggest that you follow:
class Agenda(object):
def __init__(self):
self.events = []
def append(self, event):
self.events.append(event)
class Patient(object):
def __init__(self, name, room):
self.name = name
self.room = room
def get_patient(self):
print(self.name)
print(self.room)
class Specialist(object):
def __init__(self, name, specialization):
self.name = name
self.specialization = specialization
self.timetable = Agenda()
def add_to_timetable(self, patient):
self.timetable.append(patient)
def get_specialist(self):
print(self.name)
print(self.specialization)
print(self.timetable)
specialist1 = Specialist("Dr. John", "Hematology")
patient1 = Patient("Michael", "101")
specialist1.add_to_timetable(patient1)
I'm not too sure what you're trying to accomplish here with method that just print values or with the makeAgenda class, but here's how you can get Michael in Dr. John's list:
specialist1.timetable.append(patient1.name)

Class import and assignment in Python

If I am creating a class below, can someone please explain the proper way to create the instance and also pass in the arguments. I though that I would be able to pass in the initial arguments at time of initiation but cannot seem to get this to work. Below is an example of the class:
Class Course(object):
"""
Represents a University course
"""
def _init_(self, name, teacher, description):
self.name = name
self.teacher= price
self.description = description
def _str_(self):
return "{name} ({desc}): {teacher:}".format(name=self.name,
desc=self.description, teacher=self.teacher)
So in my program I'd like to create an instance which I though I do by using something like class = Course().
But isn't there a way to initiate the 3 variables at the same time? Something along the lines of class('Math101', 'Dr. Know Nothing', 'Learning is Fun') ?
Then I can just print class and get my desired output string as defined from within the class? I might be missing an import somewhere which is also confusing to me if I need to import modules or with a class all I need to do is the initial class = Course() ?
You have to declare special methods with double underscores: __init__, not _init_. And then, when creating an object, you have to pass the arguments like: course1 = Course(...parameters...):
class Course(object):
"""
Represents a University course
"""
def __init__(self, name, teacher, description):
self.name = name
self.teacher = teacher
self.description = description
def __str__(self):
return "{name} ({desc}): {teacher:}".format(name = self.name,
desc = self.description, teacher = self.teacher)
course1 = Course('Math101', 'Dr. Know Nothing', 'Learning is Fun')
print course1
Output:
Math101 (Learning is Fun): Dr. Know Nothing
Notes:
The Python keyword to create a class is class, not Class. Python is case-sensitive for keywords.
You were assigning price to self.teacher, which would lead in an error because price is not declared anywhere. I think it's just a typo. You may use self.teacher = teacher instead.
You must not use Python keywords (reserved names) as name of variables, because if you did, you would be hiding those keywords, which would lead into problems.
First things first, you need to double your underscores:
def __init__(self, ...):
// whatever
def __str__(self, ...):
// whatever
and lowercase your Class: class Course instead of Class Course.
Now you can use your class like this:
course = Course('Math101', 'Dr. Know Nothing', 'Learning is Fun')
print course

Categories