Peter Siebel - Practical Common Lisp
Здесь есть возможность читать онлайн «Peter Siebel - Practical Common Lisp» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 2005, ISBN: 2005, Издательство: Apress, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Practical Common Lisp
- Автор:
- Издательство:Apress
- Жанр:
- Год:2005
- ISBN:1-59059-239-5
- Рейтинг книги:4 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 80
- 1
- 2
- 3
- 4
- 5
Practical Common Lisp: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Practical Common Lisp»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
Practical Common Lisp — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Practical Common Lisp», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
DEFCLASS
You create user-defined classes with the DEFCLASS
macro. Because behaviors are associated with a class by defining generic functions and methods specialized on the class, DEFCLASS
is responsible only for defining the class as a data type.
The three facets of the class as a data type are its name, its relation to other classes, and the names of the slots that make up instances of the class. [182] In other object-oriented languages, slots might be called fields , member variables , or attributes .
The basic form of a DEFCLASS
is quite simple.
(defclass name ( direct-superclass-name *)
( slot-specifier *))
What Are "User-Defined Classes"? |
The term user-defined classes isn't a term from the language standard—technically what I'm talking about when I say user-defined classes are classes that subclass |
As with functions and variables, you can use any symbol as the name of a new class. [183] As when naming functions and variables, it's not quite true that you can use any symbol as a class name—you can't use names defined by the language standard. You'll see in Chapter 21 how to avoid such name conflicts.
Class names are in a separate namespace from both functions and variables, so you can have a class, function, and variable all with the same name. You'll use the class name as the argument to MAKE-INSTANCE
, the function that creates new instances of user-defined classes.
The direct-superclass-names specify the classes of which the new class is a subclass. If no superclasses are listed, the new class will directly subclass STANDARD-OBJECT
. Any classes listed must be other user-defined classes, which ensures that each new class is ultimately descended from STANDARD-OBJECT
. STANDARD-OBJECT
in turn subclasses T
, so all user-defined classes are part of the single class hierarchy that also contains all the built-in classes.
Eliding the slot specifiers for a moment, the DEFCLASS
forms of some of the classes you used in the previous chapter might look like this:
(defclass bank-account () ...)
(defclass checking-account (bank-account) ...)
(defclass savings-account (bank-account) ...)
I'll discuss in the section "Multiple Inheritance" what it means to list more than one direct superclass in direct-superclass-names .
Slot Specifiers
The bulk of a DEFCLASS
form consists of the list of slot specifiers. Each slot specifier defines a slot that will be part of each instance of the class. Each slot in an instance is a place that can hold a value, which can be accessed using the SLOT-VALUE
function. SLOT-VALUE
takes an object and the name of a slot as arguments and returns the value of the named slot in the given object. It can be used with 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
and balance
, like this:
(defclass bank-account ()
(customer-name
balance))
Each instance of this class will contain two slots, one to hold the name of the customer the account belongs to and another to hold the current balance. With this definition, you can create new bank-account
objects using MAKE-INSTANCE
.
(make-instance 'bank-account) ==> #
The argument to MAKE-INSTANCE
is the name of the class to instantiate, and the value returned is the new object. [184] 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 .
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 objects will be created with their 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)) ==> *ACCOUNT*
(setf (slot-value *account* 'customer-name) "John Doe") ==> "John Doe"
(setf (slot-value *account* 'balance) 1000) ==> 1000
Now you can access the value of the slots.
(slot-value *account* 'customer-name) ==> "John Doe"
Интервал:
Закладка:
Похожие книги на «Practical Common Lisp»
Представляем Вашему вниманию похожие книги на «Practical Common Lisp» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Practical Common Lisp» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.