Associating methods with properties
Suppose you want to associate a public property ‘x’ with a private instance
member. Here’s how it’s done in python.
class C(object):
def __getx(self):
return self.__x
def __setx(self, x):
self.__x = x
x = property(__getx, __setx)
def init(self):
self.__x = 0
c = C()
c.x = 22
c.x
22
… and here’s how it’s done in ruby.
class C
attr_accessor :x
end
irb(main):024:0> c.x = 34
34
irb(main):025:0> c.x
34
irb(main):026:0>
The python is simplified if you used the attribute ‘x’ instead of access
methods. This isn’t a great solution either because you’re exposing the
internals of the object. That brings us to privacy, which always feels like
bit of a kludge in python.
class A:
… def init(self):
… self.x = 0
… self.__private_member = 0
…
a = A()
a.x
0
a.x = 4
a.x
4
It all boils down to how OO the language is, but ruby objects feel more
natural to me.
Neil.