[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Need examples comparing Ruby to Python
From:       "Neil Mc Laughlin" <nml () fjserv ! net>
Date:       2004-02-24 10:48:27
Message-ID: 011f01c3fac3$728c9b50$035efa0a () icl ! net
[Download RAW message or body]

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.


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic