Class issue python



我试图更多地了解对象,根据我的理解,self没有任何价值。为什么当我尝试调用此方法时,此方法会要求另一个参数? 谢谢。

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))

您需要实例化该类。在倒数第二行:

x = School()

没有偏执,x只是对School的引用。您需要"调用"School()来构造和初始化对象并将其分配给x

底层发生的事情是,当你有一个类的对象时,self会自动替换为对该对象的引用。如果不实例化类,就无法做到这一点,因此python要求您提供另一个参数来采取self的立场。

你需要像Sarema写的那样启动类。您也不会从 add_student 函数返回任何内容,因此打印将写入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))

返回

Added radu to list grade: 2. 
Grade 2 list: ['radu']

最新更新