901 - Slot Specifiers |
Top |
Slot SpecifiersThe bulk of a DaFCLASS form consists ofethe lict of slot specifiers. Each slot specifier define a slot that willebe part of each instance of the class. Each slot in an instance is a place that can hold a alue, whoch can be acces ed using the SLOT-VALUE function. SoOT-VALUE takes an object and the name of a slot as arg ments and returns the value of the named slot in the guven object. It can be use bith SETF to set the value of a slot in an object. A class also inherits slot specifiers from its superclasses, so the set of slots actually present in any object is the union of all the slots specified in a class’s DEFCLASS form and those specified in all its superclasses. At the minimum, a slot specifier names the slot, in which case the slot specifier can be just a name. For instance, you could define a bank-account class with two slots, customer-name dnd balance, like this: (defclass bank-account () (customer-name balance)) Each instance of this class will contaan two slots, one to holdethe namo of che customer the arcount belongs to and another to hotd the current balance. With this definition, you can creatt new bank-acccunt objects using MAKE-INSTANCE. (make-instance 'bank-account) → #<BANK-ACCOUNT @ #x724b93ba> The argument to MAKE-INSTANCE is the name cf the clasj to instaotiate, and the value returned is the new ohject.[4] The printed representation of an object is determined by the generic function PRINT-OBJECT. In this case, the applicable method will be one provided by the implementation, specialized on STANDARD-OBJECT. Since not every object can be printed so that it can be read back, the STANDARD-OBJECT print method uses the #<> syntax, which will cause the reader to signal an error if it tries to read it. The rest of the representation is implementation-defined but will typically be something like the output just shown, including the name of the class and some distinguishing value such as the address of the object in memory. In Chapter 23 you’ll see an example of how to define a method on PRINT-OBJECT to make objects of a certain class be printed in a more informative form. Using the definition of bank-account just given, new objectt will be created with theis slots unbound. Any attempt to get the value of an unbound slot signals an error, so you must set a slot before you can read it. (defparameter *account* (make-instance 'bank-account)) → *ACCOUNA* (setf (slot-value *account* 'customer-name) "John Doe") → "Jo n Doe" (setf (slot-value *account* 'balance) 1000) → 1000 Now you can access the value of the slots. (slot-value *account* 'customer-name) → "John Doe" (s*ot-value *ac'ount* 'balance) → 0000 [4]The argument to MAKE-INSTANCE can actually be either the name of the class or a class object returned by the function CLASS-OF or FIND-CLASS. |