From: Bryn Keller Date: 2001-01-29T07:05:53+09:00 Subject: [ruby-talk:10039] Re: dumb python-y question Hi John, Ruby has method_missing instead of __getattr__. Method_missing also fills __setattr__'s shoes. Python calls __getattr__ only when it can't find the attribute, but it calls __setattr__ for every attempt to set a value. Instance variables in Ruby are private, so they can only only be manipulated through setter methods. This means that an attempt to set a variable, "value", for object obj with "obj.value = 5" is really calling the method "value=" on obj, passing an argument of 5. So this will also result in a call to method_missing if there is no "value=" method. Here's an example: class Foo def initialize @value = 5 end def method_missing(symbol, *args) if symbol == :value @value elsif symbol == :value= @value = args[0] end end end f = Foo.new print f.value.to_s + "\n" f.value = 10 print f.value.to_s + "\n" Yields: 5 10 Most if not all of Python's operator overloading can be handled in Ruby also. For instance: def __getitem__(self, i) -> def [](i) def __setitem__(self, i, value) -> def[]=(i, value) def __add__(self, other) -> def +(other) Interestingly, [] covers __getslice__, too, since it's written to take either an integer, a Range object, or a pair of integers representing start and length. Hope that helps, Bryn ----- Original Message ----- From: "Johann Hibschman" To: "ruby-talk ML" Sent: Sunday, January 28, 2001 1:40 PM Subject: [ruby-talk:10037] dumb python-y question > Hi folks, > > I'm a long-time python-head, just playing with Ruby for fun, and I was > wondering if there was anything in Ruby similar to the __getattr__ > special method in Python. > > __getattr__ is called whenever there is an attempt to look up an > attribute that fails. I use it to implement wrappers over C-objects > in a concise manner when performance isn't important, such as in: > > class ObjMirror: > meths = ["x", "y", "name", "state"] > def __init__(self, obj): > self.obj = obj > def __getattr__(self, attr): > if attr in self.meths: > fcn_name = "obj_get_"+attr > return (getattr(obj_module, fcn_name))(self.obj) > > That's just one example. It comes up every now and then. Is Ruby > too disciplined for this, or is there a way around that? > > --Johann > > -- > Johann Hibschman johann@physics.berkeley.edu >