Add a variable to a class instance at runtime: Difference between revisions
Add a variable to a class instance at runtime (view source)
Revision as of 09:20, 6 November 2023
, 6 months ago→{{header|Wren}}: Changed to Wren S/H
(Add a variable to a class instance at runtime) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(10 intermediate revisions by 8 users not shown) | |||
Line 7:
=={{header|ActionScript}}==
In ActionScript this can be done using an Object object
<
object.foo = "bar";</
Or by creating a dynamic class
<
{
public dynamic class Foo
Line 16:
// ...
}
}</
<
foo.bar = "zap";</
=={{header|Ada}}==
Ada is not a dynamically typed language. Yet it supports mix-in inheritance, run-time inheritance and interfaces. These three allow us to achieve the desired effect, however questionably useful it could be. The example declares an interface of the class (Class). Then a concrete type is created (Base). The object E is an instance of Base. Later, at the run time, a new type Monkey_Patch is created such that it refers to E and implements the class interface per delegation to E. Monkey_Patch has a new integer member Foo and EE is an instance of Monkey_Path. For the user EE appears as E with Foo.
<
procedure Dynamic is
Line 61:
Put_Line (EE.Boo & " with" & Integer'Image (EE.Foo));
end;
end Dynamic;</
Sample output:
<pre>
I am Class with 1
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">define :myClass [name,surname][]
myInstance: to :myClass ["John" "Doe"]
print myInstance
myInstance\age: 35
print myInstance</syntaxhighlight>
{{out}}
<pre>[name:John surname:Doe]
[name:John surname:Doe age:35]</pre>
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
<
e.foo := 1 </
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
It's not really intended that you should do this, but if you must you can:
<
REM Create a base class with no members:
Line 105 ⟶ 120:
IF EVAL("FNassign(" + v$ + "," + n$ + ")")
ENDPROC
DEF FNassign(RETURN n, v) : n = v : = 0</
=={{header|Bracmat}}==
This solution saves the original members and methods in a variable, using pattern matching. Then, using macro expansion, a new object is created with an additional member variable and also an additional method. Because the new object is assigned to the same variable as the original object, the original object ceases to exist.
<
= (aMember=) (aMethod=.!(its.aMember))
)
Line 134 ⟶ 149:
& out$("aMember contains:" (object..aMethod)$)
& out$("anotherMember contains:" (object..anotherMethod)$)
&);</
Output:
<
(object=
=(aMember=) (aMethod=.!(its.aMember)));
Line 150 ⟶ 165:
Call both methods and output their return values.
aMember contains: A value
anotherMember contains: some other value</
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|4.0}}
<
//
// Program.cs - DynamicClassVariable
Line 190 ⟶ 205:
#endregion
}
}</
{{out}}
Line 197 ⟶ 212:
=={{header|CoffeeScript}}==
<
# You can dynamically add attributes to objects.
Line 215 ⟶ 230:
e.yo = -> "baz"
console.log e.foo, e.yo()
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 223 ⟶ 238:
{{libheader|Closer to MOP}}
<
(change-class instance
(make-instance 'standard-class
:direct-superclasses (list (class-of instance))
:direct-slots slots)))</
Example:
<
(new-slots '((:name xenu :initargs (:xenu)))))
(augment-instance-with-slots instance new-slots)
Line 242 ⟶ 257:
BAR = 42
BAZ = 69
XENU = 666</
The following REPL transcript (from [[LispWorks]]) 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].
Line 271 ⟶ 286:
=={{header|D}}==
<
private T[string] vars;
Line 301 ⟶ 316:
writeln(d2.a, " ", d2.b, " ", d2.c);
immutable int x = d2.b.get!int;
}</
{{out}}
<pre>10.5 20.2
Hello 11 ['x':2, 'y':4]</pre>
If you want Dynamic to be a class the code is similar. If the attribute names aren't known at compile-time, you have to use a more normal syntax:
<
struct Dyn {
Line 318 ⟶ 333:
d[attribute_name] = "something";
writeln(d[attribute_name]);
}</
{{out}}
<pre>something</pre>
Line 325 ⟶ 340:
ELENA does not support adding a field at run-time but it can be simulated with the help of a mix-in.
ELENA
<
class Extender : BaseExtender
{
this
}
public program()
{
}</
{{out}}
<pre>
Line 361 ⟶ 376:
'''Array:'''
In this example we add a function (which prints out the content of the array) and a new value. While we are not technically adding a "variable", this example is presented to show similar type of functionality.
<
vect.dump = function ()
for n in [0: self.len()]
Line 368 ⟶ 383:
end
vect += 'delta'
vect.dump()</
Output from the above:
<
1: beta
2: gamma
3: delta</
'''Dictionary:'''
In this example we will add a variable through the use of an object from a bless'ed dictionary. We create a new variable called 'newVar' at runtime and assign a string to it. Additionally we assign an external, to the object, function (sub_func) to the variable 'sub'.
<
self['prop'] -= value
return self.prop
Line 390 ⟶ 405:
])
dict[ 'newVar' ] = "I'm Rich In Data"</
=={{header|FBSL}}==
FBSL class instances aren't expandable with additional, directly accessible public methods at runtime once the class template is defined in the user code. But FBSL has an extremely powerful feature -- an ExecLine() function -- which permits the user to execute any additional code on the fly either privately (bypassing the main code flow) or publicly (interacting with the main code). ExecLine() can be used for a variety of applications from the fine-tuning of current tasks to designing application plug-ins or completely standalone code debuggers. The following class instance may be stuffed up at runtime with any code from simple variables to executable private methods and properties.
<
CLASS Growable
Line 424 ⟶ 439:
PRINT Sponge.Yield()
PAUSE</
'''Output:'''
1234567890
Line 436 ⟶ 451:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<
include FMS-SILib.f
Line 466 ⟶ 481:
main \ => Now is the time 3.14159
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
' Class ... End Class
' Esta característica aún no está implementada en el compilador.
</syntaxhighlight>
Line 484 ⟶ 499:
However, as in the case of Groovy and Kotlin, we can ''make it appear'' as though fields are being added at runtime by using the built-in map type. For example:
<
import (
Line 532 ⟶ 547:
}
}
}</
{{out}}
Line 553 ⟶ 568:
Any [[Groovy]] class that implements "''Object get(String)''" and "''void set(String, Object)''" will have the '''apparent''' capability to add new properties. However, this capability will only work as expected with an appropriate implementation, backed by a Map object or something very much like a Map.
<
final x = { it + 25 }
private map = new HashMap()
Object get(String key) { map[key] }
void set(String key, Object value) { map[key] = value }
}</
Test:
<
a.y = 55
a.z = { println (new Date()); Thread.sleep 5000 }
Line 569 ⟶ 584:
(0..2).each(a.z)
println a.q</
Output:
Line 580 ⟶ 595:
=={{header|Icon}} and {{header|Unicon}}==
Unicon implements object environments with records and supporting procedures for creation, initialization, and methods. To modify an instance you must create a new record then copy, amend, and replace it. Strictly speaking we can't guarantee the replace as there is no way to modify the existing object and we are creating a new instance with extensions. The procedures ''constructor'' and ''fieldnames'' are needed. This example doesn't do error checking. Here ''extend'' takes three arguments, the class instance, a list of new variable names as strings, and an optional list of new values to be assigned. The new instance is returned and the object is replaced by assignment. The caveat here is that if the object was assigned to anything else we will now have two objects floating around with possible side effects. As written this isn't safe from name collisions - aside from local declarations the use of a fixed constructor name uses the global name space. There is a final caveat that needs to be observed - if future implementations of objects change then this could easily stop working.
''Note:'' Unicon can be translated via a command line switch into icon which allows for classes to be shared with Icon code (assuming no other incompatibilities exist).
<
link ximage
Line 611 ⟶ 625:
x[newvars[i]] := newvals[i] # add new vars = values
return x
end</
{{libheader|Icon Programming Library}}
Line 642 ⟶ 656:
All "instance variables" (or slots in Io nomenclature) are created at runtime.
<
e := Empty clone
e foo := 1</
=={{header|J}}==
If you assign a value to the name which references a property of a class instance, that name within that instance gets that value.
<
V__C=: 0 NB. ensure the class exists
OBJ1=:conew 'exampleclass' NB. create an instance of our class
Line 662 ⟶ 676:
0
W__OBJ2 NB. our other instance does not
|value error</
=={{header|Java}}==
Adding variables to an object at runtime is not possible in Java which is a statically typed language requiring the names of all class variables to be known at compile time.
However, we can make it appear as though variables are being added at runtime by using a Map or similar structure.
<syntaxhighlight lang="java">
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public final class AddVariableToClassInstanceAtRuntime {
public static void main(String[] args) {
Demonstration demo = new Demonstration();
System.out.println("Create two variables at runtime: ");
Scanner scanner = new Scanner(System.in);
for ( int i = 1; i <= 2; i++ ) {
System.out.println(" Variable number " + i + ":");
System.out.print(" Enter name: ");
String name = scanner.nextLine();
System.out.print(" Enter value: ");
String value = scanner.nextLine();
demo.runtimeVariables.put(name, value);
System.out.println();
}
scanner.close();
System.out.println("Two new runtime variables appear to have been created.");
for ( Map.Entry<String, Object> entry : demo.runtimeVariables.entrySet() ) {
System.out.println("Variable " + entry.getKey() + " = " + entry.getValue());
}
}
}
final class Demonstration {
Map<String, Object> runtimeVariables = new HashMap<String, Object>();
}
</syntaxhighlight>
{{ out }}
<pre>
Create two variables at runtime:
Variable number 1:
Enter name: Test
Enter value: 42
Variable number 2:
Enter name: Item
Enter value: 3.14
Two new runtime variables appear to have been created.
Variable Item = 3.14
Variable Test = 42
</pre>
=={{header|JavaScript}}==
This kind of thing is fundamental to JavaScript, as it's a prototype-based language rather than a class-based one.
<
e.foo = 1
e["bar"] = 2 // name specified at runtime</
=={{header|jq}}==
jq's "+" operator can be used to add a key/value pair (or to add multiple key-value pairs) to an existing object at runtime, but
jq is a functional programming language, and objects themselves cannot be altered. Thus it may be helpful to introduce a variable, since the value of a variable can in effect be updated. For example:
<
</
A Javascript-like syntax can also be used to add (or update) a key, for example:<
# or equivalently:
$a|.["c"] = 3</
=={{header|Julia}}==
Line 687 ⟶ 757:
For example, consider the below JSON input data for a program processing phone numbers,
where the type of phone numbers for the person is unknown until run-time:
<
{"phoneNumbers": [
{
Line 701 ⟶ 771:
"number": "123 456-7890"
}]}
</syntaxhighlight>
Add the data into a class member that is declared as a Dict structure:
<syntaxhighlight lang="julia">
mutable struct Contact
name::String
Line 711 ⟶ 781:
person = Contact("Jane Doe", Dict())
person.phonenumber["home"] = "212 555-1234"
</syntaxhighlight>
=={{header|Kotlin}}==
Line 718 ⟶ 788:
However, as in the case of Groovy, we can ''make it appear'' as though variables are being added at runtime by using a Map or similar structure. For example:
<
class SomeClass {
Line 747 ⟶ 817:
}
}
}</
{{out}}
Line 768 ⟶ 838:
Latitude is prototype-oriented, so adding slots at runtime is very straightforward and common.
<
;; Name known at compile-time.
Line 774 ⟶ 844:
;; Name known at runtime.
myObject slot 'foo = "bar".</
=={{header|Lingo}}==
<
put obj.foo
Line 785 ⟶ 855:
obj.setProp(#bar, "BAR")
put obj.bar
-- "BAR"</
=={{header|Logtalk}}==
Line 792 ⟶ 862:
The following example uses a prototype for simplicity.
<
% we start by defining an empty object
:- object(foo).
Line 811 ⟶ 881:
:- end_category.
</syntaxhighlight>
We can test our example by compiling and loading the two entities above and then querying the object:
<
| ?- foo::bar(X).
X = 1 ;
Line 821 ⟶ 891:
X = 3
true
</syntaxhighlight>
=={{header|LOLCODE}}==
<tt>BUKKIT</tt>s (the all-purpose container type) can be added to at any point during execution, and the <tt>SRS</tt> operator permits the creation of identifiers from strings. This program and its output demonstrate both by prompting the user for a name and a value, modifying the object accordingly, and then printing the value of the new variable.
<
I HAS A object ITZ A BUKKIT
Line 845 ⟶ 915:
IM OUTTA YR interface
KTHXBYE</
Example run:
<pre>R U WANTIN 2 (A)DD A VAR OR (P)RINT 1? A
Line 855 ⟶ 925:
=={{header|Lua}}==
<
empty.foo = 1</
=={{header|M2000 Interpreter}}==
Adding y member to an object with a x member which made by a class alfa (a global function). We can make m as a copy of this new group (which is in a container, in a(3)). We can make a pointer to A(3) and handle the new member.
<syntaxhighlight lang="m2000 interpreter">
Module checkit {
class alfa {
Line 894 ⟶ 964:
}
checkit
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica doesn't rally have classes, so it doesn't have class variables. However, many rules can be applied to a single tag, so it has some aspects similar to a class. With that definition, adding a class variable is similar to adding a rule:
<syntaxhighlight lang="mathematica">
f[a]=1;
f[b]=2;
f[a]=3;
? f</
Output:
Global`f
Line 913 ⟶ 983:
If the name of the variable to add is known at compile time, then this is just standard class construction:
<
empty.foo = 1</
If the name of the variable to add is itself in a variable, then instead of dot syntax, use normal indexing:
<
varName = "foo"
empty[varName] = 1</
Either method results in a perfectly ordinary class or instance (there is no technical distinction between these in MiniScript), which can be used as usual by subsequent code.
Line 926 ⟶ 996:
=={{header|Morfa}}==
To emulate adding a variable to a class instance, Morfa uses user-defined operators <tt>`</tt> and <tt><-</tt>.
<
import morfa.base;
Line 989 ⟶ 1,059:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 996 ⟶ 1,066:
=={{header|Nim}}==
<
{.experimental: "dotOperators".}
template `.=`(js: JsonNode, field: untyped, value: untyped) =
Line 1,005 ⟶ 1,075:
echo(obj.foo)
obj.key = 3
echo(obj.key)</
{{out}}
<pre>
Line 1,017 ⟶ 1,087:
You can put associative references on any object. You can put multiple ones on the same object. They are indexed by a pointer key (typically the address of some dummy variable). You use the functions <code>objc_getAssociatedObject()</code> and <code>objc_setAssociatedObject</code> to get and set them, respectively.
<
#import <objc/runtime.h>
Line 1,036 ⟶ 1,106:
}
return 0;
}</
You can also use a selector as the key, since two selectors with the same content are guaranteed to be equal:
<
#import <objc/runtime.h>
Line 1,056 ⟶ 1,126:
}
return 0;
}</
=={{header|Octave}}==
Octave is dynamically typed, and can have fields added in two methods:
<
% Given struct "test"
test.b=1;
test = setfield (test, "c", 3);
</syntaxhighlight>
=={{header|ooRexx}}==
Line 1,071 ⟶ 1,141:
===Unknown Method Access===
This example traps unknown method calls, then sets or retrieves the values in an encapsulated directory object.
<syntaxhighlight lang="oorexx">
d = .dynamicvar~new
d~foo = 123
Line 1,110 ⟶ 1,180:
self~init:.dynamicvar
</syntaxhighlight>
===Dynamic Method Definitions===
An object may be written that can dynamically add methods to itself. This example is similar to the above example, but the UNKNOWN method attaches a getter/setter pair of methods for the name triggering the UNKNOWN call. On all subsequent calls, the attribute methods will get called.
<syntaxhighlight lang="oorexx">
d = .dynamicvar~new
d~foo = 123
Line 1,151 ⟶ 1,221:
forward to(self) message(messageName) arguments(arguments)
</syntaxhighlight>
=={{header|OxygenBasic}}==
Simple implementation for making runtime members - supports integer, float and string types.
<
'=================
class fleximembers
Line 1,227 ⟶ 1,297:
a.delete
</syntaxhighlight>
=={{header|Oz}}==
Line 1,234 ⟶ 1,304:
However, classes are also first-class values and are created at runtime. Many of the tasks that are solved with "monkeypatching" in other languages, can be solved by dynamically creating classes in Oz.
<
%% Creates a new class derived from BaseClass
%% with an added feature (==public immutable attribute)
Line 1,262 ⟶ 1,332:
in
{Show Instance.bar} %% inherited feature
{Show Instance.foo} %% feature of "synthesized" class</
To add a variable number of features and attributes, you can use [http://www.mozart-oz.org/documentation/base/class.html Class.new].
=={{header|Pascal}}==
Works with FPC (tested with version 3.2.2).
This could be done by playing around with the custom variants a bit.
Let's put the following code in a separate unit:
<syntaxhighlight lang="pascal">
unit MyObjDef;
{$mode objfpc}{$h+}{$interfaces com}
interface
function MyObjCreate: Variant;
implementation
uses
Variants, Generics.Collections;
var
MyObjType: TInvokeableVariantType;
type
IMyObj = interface
procedure SetVar(const aName: string; const aValue: Variant);
function GetVar(const aName: string): Variant;
end;
TMyObj = class(TInterfacedObject, IMyObj)
strict private
FMap: specialize TDictionary<string, Variant>;
public
constructor Create;
destructor Destroy; override;
procedure SetVar(const aName: string; const aValue: Variant);
function GetVar(const aName: string): Variant;
end;
TMyData = packed record
VType: TVarType;
Dummy1: array[0..5] of Byte;
Dummy2: Pointer;
FObj: IMyObj;
end;
TMyObjType = class(TInvokeableVariantType)
procedure Clear(var V: TVarData); override;
procedure Copy(var aDst: TVarData; const aSrc: TVarData; const Indir: Boolean); override;
function GetProperty(var aDst: TVarData; const aData: TVarData; const aName: string): Boolean; override;
function SetProperty(var V: TVarData; const aName: string; const aData: TVarData): Boolean; override;
end;
function MyObjCreate: Variant;
begin
VarClear(Result);
TMyData(Result).VType := MyObjType.VarType;
TMyData(Result).FObj := TMyObj.Create;
end;
constructor TMyObj.Create;
begin
FMap := specialize TDictionary<string, Variant>.Create;
end;
destructor TMyObj.Destroy;
begin
FMap.Free;
inherited;
end;
procedure TMyObj.SetVar(const aName: string; const aValue: Variant);
begin
FMap.AddOrSetValue(LowerCase(aName), aValue);
end;
function TMyObj.GetVar(const aName: string): Variant;
begin
if not FMap.TryGetValue(LowerCase(aName), Result) then Result := Null;
end;
procedure TMyObjType.Clear(var V: TVarData);
begin
TMyData(V).FObj := nil;
V.VType := varEmpty;
end;
procedure TMyObjType.Copy(var aDst: TVarData; const aSrc: TVarData; const Indir: Boolean);
begin
VarClear(Variant(aDst));
TMyData(aDst) := TMyData(aSrc);
end;
function TMyObjType.GetProperty(var aDst: TVarData; const aData: TVarData; const aName: string): Boolean;
begin
Result := True;
Variant(aDst) := TMyData(aData).FObj.GetVar(aName);
end;
function TMyObjType.SetProperty(var V: TVarData; const aName: string; const aData: TVarData): Boolean;
begin
Result := True;
TMyData(V).FObj.SetVar(aName, Variant(aData));
end;
initialization
MyObjType := TMyObjType.Create;
finalization
MyObjType.Free;
end.
</syntaxhighlight>
And main program:
<syntaxhighlight lang="pascal">
program test;
{$mode objfpc}{$h+}
uses
MyObjDef;
var
MyObj: Variant;
begin
MyObj := MyObjCreate;
MyObj.Answer := 42;
MyObj.Foo := 'Bar';
MyObj.When := TDateTime(34121);
WriteLn(MyObj.Answer);
WriteLn(MyObj.Foo);
//check if variable names are case-insensitive, as it should be in Pascal
WriteLn(MyObj.wHen);
end.
</syntaxhighlight>
{{out}}
<pre>
42
Bar
01.06.1993
</pre>
=={{header|Perl}}==
{{works with|Perl|5.x}}
<
# Constructor. Object is hash.
Line 1,279 ⟶ 1,486:
# Set runtime variable (key => value).
$o->{'foo'} = 1;</
=={{header|Phix}}==
Line 1,286 ⟶ 1,493:
Attempting to fetch/store "jelly" on a non-dynamic class would trigger a fatal error, unless said field had been explictly defined.
Needs 0.8.1+
<!--<
<span style="color: #008080;">class</span> <span style="color: #000000;">wobbly</span> <span style="color: #000000;">dynamic</span>
<span style="color: #000080;font-style:italic;">-- (pre-define a few fields/methods if you like)</span>
Line 1,295 ⟶ 1,502:
<span style="color: #000000;">wobble<span style="color: #0000FF;">.<span style="color: #000000;">jelly</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"green"</span>
<span style="color: #0000FF;">?<span style="color: #000000;">wobble<span style="color: #0000FF;">.<span style="color: #000000;">jelly</span> <span style="color: #000080;font-style:italic;">-- "green"
<!--</
=={{header|PHP}}==
<
$e=new E();
Line 1,306 ⟶ 1,513:
$e->{"foo"} = 1; // using a runtime name
$x = "foo";
$e->$x = 1; // using a runtime name in a variable</
=={{header|PicoLisp}}==
In general, all instance variables in PicoLisp are dynamically created at
runtime.
<
-> $385605941
: (put MyObject 'newvar '(some value)) # Set variable
Line 1,318 ⟶ 1,525:
$385605941 (+MyClass)
newvar (some value)
-> $385605941</
=={{header|Pike}}==
Pike does not allow adding variables to existing objects, but we can design a class that allows us to add variables.
<
{
mapping variables = ([]);
Line 1,353 ⟶ 1,560:
"greeting"
})
</syntaxhighlight>
=={{header|Pop11}}==
Line 1,374 ⟶ 1,581:
it using the 'pop11_compile' procedure.
<
define :class foo;
Line 1,401 ⟶ 1,608:
met1(bar) => ;;; default value -- false
"baz" -> met1(bar);
met1(bar) => ;;; new value</
=={{header|PowerShell}}==
PowerShell allows extending arbitrary object instances at runtime with the <code>Add-Member</code> cmdlet. The following example adds a property ''Title'' to an integer:
<
| Add-Member -PassThru `
NoteProperty `
Title `
"The answer to the question about life, the universe and everything"</
Now that property can be accessed:
<pre>PS> $x.Title
Line 1,434 ⟶ 1,641:
=={{header|Python}}==
<
pass
e = empty()</
If the variable (attribute) name is known at "compile" time (hard-coded):
<
If the variable name is determined at runtime:
<
'''Note:''' Somewhat counter-intuitively one cannot simply use ''e = object(); e.foo = 1'' because the Python base ''object'' (the ultimate ancestor to all new-style classes) will raise attribute exceptions. However, any normal derivatives of ''object'' can be "monkey patched" at will.
Line 1,449 ⟶ 1,656:
Because functions are first class objects in Python one can not only add variables to instances. One can add or replace functionality to an instance. Doing so is tricky if one wishes to refer back to other instance attributes since there's no "magic" binding back to "self." One trick is to dynamically define the function to be added, nested within the function that applies the patch like so:
<
def __init__(this):
this.foo = "whatever"
Line 1,461 ⟶ 1,668:
patch_empty(e)
e.print_output()
# >>> whatever</
: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.
Line 1,468 ⟶ 1,675:
{{works with|Rakudo|2015.12}}
You can add variables/methods to a class at runtime by composing in a role. The role only affects that instance, though it is inheritable. An object created from an existing object will inherit any roles composed in with values set to those at the time the role was created. If you want to keep changed values in the new object, clone it instead.
<syntaxhighlight lang="raku"
my $object = Bar.new; # new instance
Line 1,489 ⟶ 1,696:
my $that = $object.clone; # instantiate a new Bar derived from $object copying any variables
say $that.foo; # 5 - value from the cloned object</
That's what's going on underneath, but often people just mix in an anonymous role directly using the <tt>but</tt> operator. Here we'll mix an attribute into a normal integer.
<syntaxhighlight lang="raku"
say $lue; # 42
say $lue.answer; # Life, the Universe, and Everything</
On the other hand, mixins are frowned upon when it is possible to compose roles directly into classes (as with Smalltalk traits), so that you get method collision detection at compile time. If you want to change a class at run time, you can also use monkey patching:
<syntaxhighlight lang="raku"
augment class Int {
method answer { "Life, the Universe, and Everything" }
}
say 42.answer; # Life, the Universe, and Everything</
This practice, though allowed, is considered to be Evil Action at a Distance.
=={{header|REBOL}}==
<
REBOL [
Title: "Add Variables to Class at Runtime"
Line 1,554 ⟶ 1,761:
print [crlf "Fighter squadron:"]
foreach pilot squadron [probe pilot]
</syntaxhighlight>
=={{header|Red}}==
<
name: none
age: none
Line 1,567 ⟶ 1,774:
foreach person people [
print reduce [person/age "year old" person/name "is good at" any [select person 'skill "nothing"]]
]</
=={{header|Ring}}==
We can add an attribute (or a group of attributes) to the object state using addattribute() function
<
addattribute(o1,"x")
addattribute(o1,"y")
addattribute(o1,"z")
see o1 {x=10 y=20 z=30}
class point</
{{out}}
<pre>
Line 1,585 ⟶ 1,792:
=={{header|Ruby}}==
<
end
Line 1,597 ⟶ 1,804:
f = Empty.new
f.foo = 1 # raises NoMethodError
</syntaxhighlight>
"class << e" uses the ''singleton class'' of "e", which is an automatic subclass of Empty that has only this single instance. Therefore we added the "foo" accessor only to "e", not to other instances of Empty.
Another way of adding a method to a singleton is:
<
def yes_no.not
Line 1,610 ⟶ 1,817:
p yes_no.not # => "No"
p yes_no.not # => "Yes"
p "aaa".not # => undefined method `not' for "aaa":String (NoMethodError)</
=={{header|Scala}}==
Line 1,616 ⟶ 1,823:
Since version 2.10 Scala supports dynamic types. Dynamic types have to implement trait ''Dynamic'' and implement methods ''selectDynamic'' and ''updateDynamic''.
<
import scala.collection.mutable.HashMap
Line 1,627 ⟶ 1,834:
map(name) = value
}
}</
Sample output in the REPL:
<
a: A = A@7b20f29d
Line 1,638 ⟶ 1,845:
scala> a.foo
res10: Any = 42</
=={{header|Sidef}}==
<
var e = Empty(); # create a new class instance
e{:foo} = 42; # add variable 'foo'
say e{:foo}; # print the value of 'foo'</
=={{header|Slate}}==
Slate objects are prototypes:
<
define: #e -> Empty clone.
e addSlotNamed: #foo valued: 1.</
=={{header|Smalltalk}}==
Line 1,656 ⟶ 1,863:
This preserves object identity. (by the way: if we remember and reuse these temp classes, we get the core of Google's fast JavaScript interpreter implementation ;-)
{{works with|Smalltalk/X}} (should work with all Smalltalks, though)
<
addSlot :=
Line 1,671 ⟶ 1,878:
newObj := anonCls cloneFrom:obj.
obj become:newObj.
].</
create a 2D Point object, add a z slot, change and retrieve the z-value, finally inspect it (and see the slots).
<
addSlot value:p value:'z'.
p z:30.
p z.
p z:40.
p inspect</
The above used a block to perform this operation in privacy. In a real world application, the addSlot code would be added as an extension to the Object class, as in.
<
addSlot: slotName
Line 1,695 ⟶ 1,902:
anonCls compile:('%1:v %1 := v' bindWith:slotName).
newObj := anonCls cloneFrom:self.
self become:newObj.</
then, again create a 2D Point object, add a z slot, change and retrieve the z-value, finally inspect it (and see the slots).
<
p addSlot:'z'. "instance specific added slot"
p z:30.
Line 1,713 ⟶ 1,920:
p3 z:4.
p3 inspect. "shows 3 slots"
</
<!--
Line 1,721 ⟶ 1,928:
CG: commented the bad example; maybe the original author wants to fix it / comment on it.
<
instanceVariableNames: 'aVar'
classVariableNames: ''
Line 1,778 ⟶ 1,985:
aMonkey setX: 10 .
aMonkey inspect .
(aMonkey x) printNl .</
Output is:
Line 1,795 ⟶ 2,002:
We can use the same associated object mechanism as in Objective-C:
<
let fooKey = UnsafeMutablePointer<UInt8>.alloc(1)
Line 1,810 ⟶ 2,017:
} else {
print("no associated object")
}</
=={{header|Tcl}}==
Line 1,816 ⟶ 2,023:
The code below uses the fact that each object is implemented as a namespace, to add a ''time'' variable to an instance of ''summation'':
<
% oo::class create summation {
constructor {} {
Line 1,842 ⟶ 2,049:
% $s value time
now
%</
An alternative approach is to expose the (normally hidden) <code>varname</code> method on the object so that you can get a handle for an arbitrary variable in the object.
<
constructor {} {
variable v 0
Line 1,871 ⟶ 2,078:
% # Show that it is only in one object...
% $s2 value time
can't read "time": no such variable</
=={{header|Wren}}==
Although Wren is dynamically typed, it is not possible to add new variables (or fields as we prefer to call them) to a class at run time. We therefore follow the example of some of the other languages here and use a map field instead.
<
class Birds {
Line 1,901 ⟶ 2,108:
for (kv in birds.userFields) {
System.print(" %(kv.key) = %(kv.value)")
}</
{{out}}
Line 1,922 ⟶ 2,129:
magpie = 7
wren = 8
</pre>
=={{header|XBS}}==
<syntaxhighlight lang="xbs">set Object = {}
Object.Hello = "World";
log(Object.Hello);</syntaxhighlight>
{{out}}
<pre>
World
</pre>
=={{header|zkl}}==
Once created, class structure is fixed. However, using reflection, you can blow apart the class structure, add what ever and recompile the class (at run time). The REPL does this to store intermediate user results (defined classes, functions, variables, etc). It is ugly, slow and left as an exercise to the reader who cares.
{{omit from|6502 Assembly}}
{{omit from|
{{omit from|8086 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|ALGOL 68}}
{{omit from|Applesoft BASIC}}
{{omit from|ARM Assembly}}
{{omit from|AWK}}
{{omit from|Brainf***}}
{{omit from|C++}}
{{omit from|Clojure}}
{{omit from|C}}
{{omit from|Delphi}}
{{omit from|F Sharp}}
{{omit from|Factor}}
{{omit from|Fortran}}
{{omit from|Free Pascal}}
Line 1,941 ⟶ 2,162:
{{omit from|GUISS}}
{{omit from|Haskell}}
{{omit from|Icon}}
{{omit from|Integer BASIC}}
{{omit from|Java}}
Line 1,959 ⟶ 2,181:
{{omit from|Processing}}
{{omit from|PureBasic}}
{{omit from|Retro}}
{{omit from|Rust}}
{{omit from|R}}
{{omit from|Scheme}}
{{omit from|TI-83 BASIC}}
{{omit from|TI-89 BASIC}} <!-- Does not have objects. -->
{{omit from|UNIX Shell}}
{{omit from|Z80 Assembly}}
{{omit from|ZX Spectrum Basic}} <!-- Does not have objects. -->
|