Jump to content

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

Adding REBOL example.
(Adding REBOL example.)
Line 327:
# >>> whatever</lang>
:Note: The name ''self'' is not special; it's merely the pervasive Python convention. In this example I've deliberately used ''this'' in the class definition to underscore this fact. The nested definition could use any name for the "self" object. Because it's nested the value of the object is evaluated at the time that the patch_empty() function is run and thus the function being patched in has a valid reference to the object into which it is being inserted. Other arguments could be passed as necessary. Such techniques are not recommended; however they are possible.
 
=={{header|REBOL}}==
<lang rebol>[
REBOL [
Title: "Add Variables to Class at Runtime"
Author: oofoe
Date: 2009-12-04
URL: http://rosettacode.org/wiki/Adding_variables_to_a_class_instance_at_runtime
]
 
; As I understand it, a REBOL object can only ever have whatever
; properties it was born with. However, this is somewhat offset by the
; fact that every instance can serve as a prototype for a new object
; that also has the new parameter you want to add.
 
; Here I create an empty instance of the base object (x), then add the
; new instance variable while creating a new object prototyped from
; x. I assign the new object to x, et voila', a dynamically added
; variable.
 
x: make object! [] ; Empty object.
 
x: make x [
newvar: "forty-two" ; New property.
]
 
print "Empty object modifed with 'newvar' property:"
probe x
 
; A slightly more interesting example:
 
starfighter: make object! [
model: "unknown"
pilot: none
]
x-wing: make starfighter [
model: "Incom T-65 X-wing"
]
squadron: reduce [
make x-wing [pilot: "Luke Skywalker"]
make x-wing [pilot: "Wedge Antilles"]
make starfighter [
model: "Slayn & Korpil B-wing"
pilot: "General Salm"
]
]
 
; Adding new property here.
squadron/1: make squadron/1 [deathstar-removal-expert: yes]
 
print [crlf "Fighter squadron:"]
forall squadron [probe squadron/1]
]</lang>
 
=={{header|Ruby}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.