Class issue python
I'm trying to learn more about objects, and from what I understood, self doesn't take any value. Why does this method asks for another argument when I try to call it? Thanks.
class School:
def __init__(self):
self.roster = []
self.dicti = {1:[],
2:[],
3:[],
4:[],
5:[]}
def add_student(self,name,grade):
if name in self.dicti[grade]:
raise ValueError("The student is already added to the grade")
else:
self.dicti[grade].append(name)
x = School
print(x.add_student("radu",2))
You need to instantiate the class. In your penultimate line:
x = School()
Without the paranthesis, x
is just a reference to School
. You need to "call" School()
to construct and initialise an object and assign it to x
.
What is happening under the hood is that when you have an object of the class, self
is automatically replaced with a reference to the object. Without instantiating the class, this cannot be done, therefore python asks you to provide another argument to take the position of self
.