class Course: courses = None def __init__(self, name, credit, time): self.name = name self.credit = credit self.time = time self.courses = [] def add_course(self,course): self.courses.append(course) def print_course(self): for course in self.courses: print(course.name) def choose_class(): print(''' 1.'Advanced Mathematics', 'credit:4', 'Monday 8:30-10:10')) 2.'College English', 'credit:3', 'Tuesday 2:30-4:10' 3.'Computer programming', 'credit:4', 'Wednesday 10:30-12:10' 4.'Computer Design', 'credit:3', 'Thursday 4:30-6:10''') ch = int(input('Please choose the class that you want:')) if ch == 1: Course.add_course('Advanced Mathematics') elif ch == 2: Course.add_course('College English') elif ch == 3: Course.add_course('Computer programming') elif ch == 4: Course.add_course('Computer Design')
时间: 2023-06-16 17:07:52 浏览: 187
Bachelors-File-Submission:在我的 B.Tech 中提交的实践、文件和作业的集合
这段代码有几个问题需要修正才能正确运行:
1. courses 属性应该是一个类属性,而不是实例属性,应该在类定义时初始化,而不是在 `__init__` 方法中定义。
2. `add_course` 方法需要传入一个 `Course` 类型的参数,而不是一个字符串。
3. `choose_class` 方法应该是一个静态方法或者类方法,而不是一个普通函数。
修改后的代码如下:
```
class Course:
courses = [
Course('Advanced Mathematics', 4, 'Monday 8:30-10:10'),
Course('College English', 3, 'Tuesday 2:30-4:10'),
Course('Computer programming', 4, 'Wednesday 10:30-12:10'),
Course('Computer Design', 3, 'Thursday 4:30-6:10')
]
def __init__(self, name, credit, time):
self.name = name
self.credit = credit
self.time = time
@classmethod
def add_course(cls, course):
cls.courses.append(course)
@classmethod
def print_courses(cls):
for course in cls.courses:
print(course.name)
@staticmethod
def choose_class():
print('''
1. Advanced Mathematics, credit:4, Monday 8:30-10:10
2. College English, credit:3, Tuesday 2:30-4:10
3. Computer programming, credit:4, Wednesday 10:30-12:10
4. Computer Design, credit:3, Thursday 4:30-6:10
''')
ch = int(input('Please choose the class that you want:'))
if ch == 1:
Course.add_course(Course('Advanced Mathematics', 4, 'Monday 8:30-10:10'))
elif ch == 2:
Course.add_course(Course('College English', 3, 'Tuesday 2:30-4:10'))
elif ch == 3:
Course.add_course(Course('Computer programming', 4, 'Wednesday 10:30-12:10'))
elif ch == 4:
Course.add_course(Course('Computer Design', 3, 'Thursday 4:30-6:10'))
```
这样,我们就可以通过调用 `Course.choose_class()` 方法来选择课程,调用 `Course.print_courses()` 方法来打印所有已选的课程了。
阅读全文