lispEn 2018-02-12 18:13:40

Common lisp make-instance

When you call  make-instance, Lisp (CLOS) performs the following steps.

  •     Combines the initargs you supply to make-instance with the default values for any initargs you do not explicitly supply. The result is a defaulted initargs list.
  •     Ensures that all initargs names in the default initarg list are valid, and signal an error if they are not. If :allow-other-keys is provided as true in the call to make-instance, all initarg names are valid
  •     Allocates storage for the instance and creates  an instance whose slots are all unbound.
  •     Applies the initialize-instance generic function to the newly created instance and the defaulted initarg list. The default primary method for initialize-instance does the following.

                   -    Initializes slots according to the defaulted initarg list

                   -   Initializes any slots that have :initforma and are still unbound.

  •   Returns the initialized instance

A simple example:

;;define the class person

(defclass person ()

  ((name :accessor name :initarg :name :initform "Some name")

   (lastname :accessor lastname :initarg :lastname :initform "Some lastname")

   (age :accessor age :initarg :age)))

;; a global variable to save the instance

(defparameter *person* nil)

;; a method to display the information

(defmethod display-person-information ((object person))

  (format t "Name:~a, Lastname ~a, Age: ~a~%" (name object) (lastname object) (age object)))

;; make-instance examples

(setf *person* (make-instance 'person :name "Juan" :lastname "Reynoso" :age 32))

;; display the information:

(display-person-information *person*)

Name:Juan, Lastname Reynoso, Age: 32

;; another example

(setf *person* (make-instance 'person  :age 100))

;; display the information:

(display-person-information *person*)

Name:Some name, Lastname Some lastname, Age: 100

More information: