我可能会问一个愚蠢的问题。我刚刚开始学习Python。
我有一个简单的python脚本,该脚本使用两个方法定义了一个类:add_course
和write_to_file
:
class School:
courses=["Math","Physics","Chemical"]
def __init__(self):
return
def add_course(self, course):
if course not in self.course:
self.course.append(course)
def write_to_file():
course_file = open('courses.csv', 'w+')
wr = csv.writer(course_file, delimiter='\t')
writer.writerow(self.courses)
// create a School instance
school = School()
// add course
school.add_course("test")
school.add_course("test2")
school.add_course("test")
// write course to file
school.write_to_file()
我运行上面的脚本,然后,打开courses.csv文件,看不到“ test”和“ test2”,但是我可以看到课程“ Math”,“ Physics”,“ Chemical”为什么?
当前,您已将课程添加为类级属性,但尝试将其作为实例属性进行访问,因此您必须将课程初始化移至__init__
方法中,如下面的代码片段所示:
def __init__(self):
self.courses = ["Math", "Physics", "Chemical"]
另外,您还必须修改add_course
方法以将项目追加到self.courses
而不是self.course
:
def add_course(self, course):
if course not in self.courses:
self.courses.append(course)
有关如何以及何时使用每种类型的属性的更多说明,请参见SO Python:类和实例属性之间的区别问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句