[英]Python: How to add a list into a class and append it
I am trying to add a class Department
and in this class, "courses" is supposed to be a list that I can add to with the add_course function.我正在尝试添加一个 class
Department
,在这个 class 中,“课程”应该是我可以使用 add_course function 添加到的列表。 Is there a way to tell python that "courses" is a list and then use .append
to add new courses to this list?有没有办法告诉 python “课程”是一个列表,然后使用
.append
将新课程添加到此列表中?
class Department:
def __init__(self, name, code, courses):
self.name = name
self.code = code
self.courses = courses
courses.tolist()
def add_course(self, course):
self.course = course
courses.append(course)
Assuming that you will always be passing in courses, you could try this:假设你总是会通过课程,你可以试试这个:
class Department:
def __init__(self, name, code, courses=None):
self.name = name
self.code = code
if isinstance(courses, list):
self.courses = courses
elif courses is None:
self.courses = []
else:
raise TypeError
def add_course(self, course):
self.courses.append(course)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.