Jump to content

Add a variable to a class instance at runtime: Difference between revisions

CLOS slot addition via class redefinition
m (omit from fortran)
(CLOS slot addition via class redefinition)
Line 71:
I am Class with 1
</pre>
 
=={{header|Common Lisp}}==
 
The following REPL transcript shows the definition of a class <code>some-class</code> with no slots, and the creation of an instance of the class. The first attempt to access the slot named <code>slot1</code> signals an error as there is no such slot. Then the class is redefined to have such a slot, and with a default value of 23. Attempting to access the slot in the preëxisting instance now gives the default value, since the slot has been added to the instance. This behavior is specified in [http://www.lispworks.com/documentation/HyperSpec/Body/04_cf.htm §4.3.6 Redefining Classes] of the [http://www.lispworks.com/documentation/HyperSpec/Front/index.htm HyperSpec].
 
<pre>CL-USER 57 > (defclass some-class () ())
#<STANDARD-CLASS SOME-CLASS 200BF63B>
 
CL-USER 58 > (defparameter *an-instance*
(make-instance 'some-class))
*AN-INSTANCE*
 
CL-USER 59 > (slot-value *an-instance* 'slot1)
 
Error: The slot SLOT1 is missing from #<SOME-CLASS 21F59E37> (of class #<STANDARD-CLASS SOME-CLASS 200BF63B>), when reading the value.
1 (abort) Return to level 0.
2 Return to top loop level 0.
 
Type :b for backtrace, :c <option number> to proceed, or :? for other options
 
CL-USER 60 : 1 > :a
 
CL-USER 61 > (defclass some-class ()
((slot1 :initform 23)))
#<STANDARD-CLASS SOME-CLASS 200BF63B>
 
CL-USER 62 > (slot-value *an-instance* 'slot1)
23</pre>
 
=={{header|Io}}==
Line 76 ⟶ 104:
 
e := Empty clone
e foo := 1
 
=={{header|JavaScript}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.