- E04 - Leadership! Google, Guido van Rossum, PSF

Hans Nowak hans at zephyrfalcon.org
Tue Jan 3 13:46:13 EST 2006


Duncan Booth wrote:

> BTW, I don't know Ruby enough to understand the example at 
> http://lazaridis.com/case/lang/ruby/base.html:
> 
> class Object
>   def meta     # adds variable "meta" to all objects in the system
> end

I don't think this is valid Ruby code, by the way...  It should probably 
be something like this:

   class Object
     attr_accessor :meta
   end

> Talker.meta = "Class meta information"
> john.meta = "Instance meta information"
> 1234.meta = 'any Instance meta information"
> 
> puts Talker.meta
> puts john.meta
> puts 1234.meta  # an integer object
> 
> With the above code what would 'puts someexpressionresultingin1234.meta' 
> output? i.e. is the attribute being set on all integers with the value 
> 1234, or just on a specific instance of an integer.

At first glance, it seems the former is true:

irb(main):021:0> class Object
irb(main):022:1>   attr_accessor :meta
irb(main):023:1> end
=> nil
irb(main):026:0> 1234.meta = "fred"
=> "fred"
irb(main):027:0> (1000+234).meta
=> "fred"
irb(main):028:0> x = 617
=> 617
irb(main):029:0> x *= 2
=> 1234
irb(main):031:0> x.meta
=> "fred"
irb(main):032:0> 3.meta
=> nil

However, inspecting the object_id (comparable to Python's id()) shows 
that all these refer to the same object:

irb(main):035:0> 1234.object_id
=> 2469
irb(main):036:0> x.object_id
=> 2469
irb(main):041:0> y = 1000
=> 1000
irb(main):042:0> y.object_id
=> 2001
irb(main):043:0> y += 234
=> 1234
irb(main):044:0> y.object_id
=> 2469

I am not an expert on Ruby internals, but it looks like these integers 
are cached.  As with Python, I don't know if one can count on this 
behavior to happen always.

-- 
Hans Nowak
http://zephyrfalcon.org/



More information about the Python-list mailing list