Trojan666
Trojan666

Reputation: 67

Add a result from class object to another class in 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.

=================================================

Upvotes: -1

Views: 1510

Answers (3)

Japjot Singh Chauhan
Japjot Singh Chauhan

Reputation: 21

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.

Upvotes: 1

Raymond Reddington
Raymond Reddington

Reputation: 1837

Basically admission is an instance method, so you should define your school instance, then add students:

school1 = School()
school1.admission(a)

Upvotes: 1

user2390182
user2390182

Reputation: 73460

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)

Upvotes: 3

Related Questions