Reputation: 59
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))
Upvotes: 1
Views: 49
Reputation: 35
You need to initiate the class as Sarema wrote. You also don't return anything from the add_student function, so the print will write None
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)
return f"Added {name} to list grade: {grade}. " \
f"\nGrade {grade} list: {self.dicti[grade]}"
x = School()
print(x.add_student("radu", 2))
returns
Added radu to list grade: 2.
Grade 2 list: ['radu']
Upvotes: 0
Reputation: 725
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
.
Upvotes: 2