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

Content deleted Content added
No edit summary
No edit summary
Line 27: Line 27:
$e->foo=1;
$e->foo=1;

=={{header|Pop11}}==

In Pop11 instance variables (slots) are specified at class creation
time and there is no way to add new slot to an instance after its
class was created. However, for most practical purposes one can
obtain desired effect in different way. Namely, except for a few
low-lever routines slots in Pop11 are accessed via getter and
setter methods. Getters and setters are like ordinary methods,
but are automatically defined and "know" low level details of
slot access. Pop11 allows dynamic definition of methods, and
one can add new methods which work as "getter" and "setter" but
do not store data directly in instance. One possibility is
to have one instance variable which contains a hastable (this
is essentially what Perl solution is doing). Another possibility
(used below) is to create na external hashtable. Adding new slots
typically make sense if slot name is only known at runtine, so
we create method definition (as a list) at runtime and compile
it using the 'pop11_compile' procedure.

<pre>
lib objectclass;

define :class foo;
enddefine;

define define_named_method(method, class);
lvars method_str = method >< '';
lvars class_str = class >< '';
lvars method_hash_str = 'hash_' >< length(class_str) >< '_'
>< class_str >< '_' >< length(method_str)
>< '_' >< method_str;
lvars method_hash = consword(method_hash_str);
pop11_compile([
lvars ^method_hash = newassoc([]);
define :method ^method(self : ^class);
^method_hash(self);
enddefine;
define :method updaterof ^method(val, self : ^class);
val -> ^method_hash(self);
enddefine;
]);
enddefine;

define_named_method("met1", "foo");
lvars bar = consfoo();
met1(bar) => ;;; default value -- false
"baz" -> met1(bar);
met1(bar) => ;;; new value
</pre>


=={{header|Python}}==
=={{header|Python}}==