Я новичок в Python объектно-ориентированном программировании. Я скопировал этот код онлайн, чтобы лучше понять, как OOP работал в Python. Вот код:
class Student:
def __init__(self, name, student_number):
## Student has-a name
self.name = name
## Student has-a student number
self.student_number = student_number
## Student has-many classes
self.classes = []
def enrol(self, course_running):
## Append the list, classes with variable course_running
self.classes.append(course_running)
## Call course_running with the add_student function in a class
course_running.add_student(self)
class Department:
def __init__(self, name, department_code):
## Department has-a name
self.name = name
## Department has-a code
self.department_code = department_code
## Department has-many courses
self.courses = {}
def add_course(self, description, course_code, credits):
self.courses[course_code] = Course(self, description, course_code, credits)
return self.courses[course_code]
class Course:
def __init__(self, description, course_code, credits, department):
## Course has-a description
self.description = description
## Course has-a code
self.course_code = course_code
## Course has-many credits
self.credits = credits
## Course has-a deparmtnet
self.department = department
## Adds the aforementioned course to the necessary DPT; it is usefull because
## it automatically adds this course to the DPT given in its parameter
self.department.add_course(self)
## Course has-many runnings
self.runnings = []
def add_running(self, year):
self.runnings.append(CourseRunning(self, year))
return self.runnings[-1]
class CourseRunning:
def __init__(self, course, year):
## CourseRunning has-a year
self.course = course
## CourseRunning has-a year
self.year = year
## CourseRunning has-many students
self.students = []
def add_student(self, student):
self.students.append(student)
maths_dept = Department("Mathematics and Applied Mathemtics", "MAM")
mam1000w = maths_dept.add_course("Mathematics 1000", "MAM1000W", 1)
mam1000w_2013 = mam1000w.add_running(2013)
bob = Student("Bob", "Smith")
bob.enrol(mam1000w_2013)
Тем не менее, я продолжаю получать эти ошибки:
Traceback (most recent call last):
File "ex42c.py", line 70, in <module>
mam1000w = maths_dept.add_course("Mathematics 1000", "MAM1000W", 1)
File "ex42c.py", line 30, in add_course
self.courses[course_code] = Course(self, description, course_code, credits)
File "ex42c.py", line 47, in __init__
self.department.add_course(self)
AttributeError: 'int' object has no attribute 'add_course'
Я изменил объект 'int' в объект 'list', а затем объект 'str' , но они дали похожие ошибки. Когда я удалил целочисленные переменные и все переменные «credit», произошла та же ошибка с переменными «course_code» и str «MAM1000W». По сути, я хочу понять, почему я не могу передать эти параметры функции.
Заранее спасибо.