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

From Rosetta Code
Content added Content deleted
(New page: {{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 r...)
 
No edit summary
Line 4: Line 4:
==[[Python]]==
==[[Python]]==
[[Category:Python]]
[[Category:Python]]
class empty(object):
class empty(object):
pass
pass


e = empty()
e = empty()
setattr(e, "foo", 1)
setattr(e, "foo", 1)
print e.foo
print e.foo


==[[Ruby]]==
==[[Ruby]]==
[[Category:Ruby]]
[[Category:Ruby]]
class Empty
class Empty
end
end
e = Empty.new
e = Empty.new
e.instance_variable_set("@foo", 1)
e.instance_variable_set("@foo", 1)
e.instance_eval("class << self; attr_accessor :foo; end")
e.instance_eval("class << self; attr_accessor :foo; end")
puts e.foo
puts e.foo

Revision as of 00:06, 18 September 2007

Task
Add a variable to a class instance at runtime
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

Python

class empty(object):
  pass
e = empty()
setattr(e, "foo", 1)
print e.foo

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