Methods
defclass provides syntax for automatically generating methods to read and write slots. Because the accessor is the most common of these methods, the whole group is called accessor methods. You can request three kinds of methods.
setf method on the named method for storing a new value.
Here is the fourth-grader class redefined using accessor methods. The accessor doesn't need to have the same name as the slot; here the accessor of the slot teacher is named fourth-grade-teacher:
? (defclass fourth-grader ()
((teacher :initarg :teacher
:initform "Mrs. Marple"
:accessor fourth-grade-teacher)
(name :initarg :name
:reader name)
(school :initarg :school
:initform "Lawrence School"
:accessor school)
(age :initarg :age
:initform 9
:accessor age)))
The :reader and :accessor methods simply provide a more abstracted alternative to slot-value and do not prevent your using slot-value as well. Creating the accessor method fourth-grade-teacher is equivalent to
?(defmethod fourth-grade-teacher ((student fourth-grader)) (slot-value student 'teacher))?(defmethod (setf fourth-grade-teacher) (new-teacher (student fourth-grader)) (setf (slot-value student 'teacher ) new-teacher))
Making an instance of fourth-grader works the same way as previously.
? (setq delia (make-instance 'fourth-grader
:teacher "Mr. Smith"
:name "Delia"))
But you can now use the accessor method fourth-grade-teacher to get the teacher of delia and the accessor method age to get the age of delia:
? (fourth-grade-teacher delia)
"Mr. Smith"
? (age delia)
9
Accessor methods create regular generic functions and can be used just like any other Lisp functions. For instance, you can combine fourth-grader methods say and school to have an instance of fourth-grader report on the school it goes to. Because all look-ups occur at run time, this works even though say was defined before fourth-grader was redefined.
? (say mariah (school mariah)) ***Lawrence School!*** NIL ? (say alisa (fourth-grade-teacher alisa)) ***Mrs. Marple!*** I have an HP calculator NIL ? (setf (age sharon) 10) 10
Generated with Harlequin WebMaker