Add a variable to a class instance at runtime: Difference between revisions
Content deleted Content added
m →{{header|Perl}}: Added works with. |
m Added to <5 category |
||
Line 1: | Line 1: | ||
[[Category:Less Than 5 Examples]]{{task}} |
|||
{{task}} |
|||
This demonstrates how to dynamically add variables to a class instance at runtime. This is useful when the methods/variables are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at [http://www.devsource.com/article2/0,1759,1928562,00.asp An Exercise in Metaprogramming with Ruby]. This is referred to as "monkeypatching" by Pythonistas and some others. It's possible in most '''dynamic''' OO languages such as Python, Ruby, and Smalltalk. |
This demonstrates how to dynamically add variables to a class instance at runtime. This is useful when the methods/variables are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at [http://www.devsource.com/article2/0,1759,1928562,00.asp An Exercise in Metaprogramming with Ruby]. This is referred to as "monkeypatching" by Pythonistas and some others. It's possible in most '''dynamic''' OO languages such as Python, Ruby, and Smalltalk. |
||
Revision as of 15:51, 22 February 2008
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
This demonstrates how to dynamically add variables to a class instance at runtime. This is useful when the methods/variables are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others. It's possible in most dynamic OO languages such as Python, Ruby, and Smalltalk.
JavaScript
e = {} // generic object e.foo = 1
Perl
package Empty; # Constructor. Object is hash. sub new { return bless {}, shift; } package main; # Object. my $o = Empty->new; # Set runtime variable (key => value). $o->{'foo'} = 1;
Python
class empty(object): pass e = empty()
If the variable name is known at "compile" time:
e.foo = 1
If the variable name is only at runtime:
setattr(e, name, value)
Ruby
class Empty end
e = Empty.new e.instance_variable_set("@foo", 1) e.instance_eval("class << self; attr_accessor :foo; end") puts e.foo