1
votes

In my program I essentially want to return the result of a method that tests for equality between two students (i.e if the number of classes both have taken is equal)

I created a class called Student. I then created two functions and defined their attributes. I'm essentially trying to compare two objects within the student class and one method needs to check for equality between the two.

class Student:


    def __init__(self, name, age, classesTaken):
        self.name = name
        self.age = age
        self.classesTaken = classesTaken

    def equals (student):
        is_equals = student.name == self.name and student.age == self.age and 
        student.classesTaken == self.classesTaken
        return is_equals


mike = Student("Mike", 21, 25)
john = Student("John", 19, 22)

#problem starts here
print (mike.equals(john))

I keep getting the error:

input Traceback (most recent call last):
File "main.py", line 18, in

print (mike.equals(john)) TypeError: equals() takes 1 positional argument but 2 were given

2
A method of a call gets called with the instance implicitly. Do def equals (self, student) instead of def equals (student)han solo
You missed to add the mandatory self arguments.Klaus D.

2 Answers

3
votes

add self to your equals function parameter

def equals (self,student):
3
votes

In python, instance methods take self as the first argument to refer to the instance their are called on:

def equals(self, student):
    # ...

that being said, you might consider overriding the dunder method __eq__:

def __eq__(self, other):
    # ...

which will allow you to test equality more pythonically via ==:

mike == john