a Python person's experience with Ruby

MonkeeSage MonkeeSage at gmail.com
Sun Dec 9 16:24:31 EST 2007


On Dec 9, 3:10 pm, I V <ivle... at gmail.com> wrote:
> On Sun, 09 Dec 2007 11:58:05 -0800, MonkeeSage wrote:
> > class A
> >   attr_accessor :a # == self.a,
> >                    # accessible to instances of A
> >   def initialize
> >     @a = "foo" # A.__a
> >                # only accessible from class scope of A
> >   end
> > end
>
> > Once again, there is no such thing as an attribute that is not a method
> > in ruby, and there is no such thing as setting an *attribute* ("=" is a
> > method also). You're trying to *re-implement* rubys mechanism in python
> > in your example, but in pythons mechanism, all attributes already have
> > built-in getter/setter. So the correct analogy is a variable that is
> > accessible from within the classes scope only (A.__a), and then exposed
> > to instances through an attribute (self.a). Your example leaves out a
> > variable accessible only from within the scope of the class, and adds a
> > new attribute accessible from the instance (_a).
>
> Either I'm not understanding you, or you're not understanding what A.__a
> means in python. A.__a is a class attribute, not an instance attribute -
> it's equivalent to @@a in ruby, not @a.

I said previously that A.__a is a class variable. Since I was only
using it to show that @a is not exposed as an attribute, I just used
A.__a, but you're right, it would have been better to use self.__a.

> If I understand what you're
> saying, a better python example to make your point might be:
>
> class A(object):
>         def __init__(self):
>                 self.__a = "foo" # equivalent to @a
>                 self.a = self.__a # exposes self.__a

Thanks.

> Except that this only allows you to access '__a' via the exposed
> attribute 'a', not bind it to a new object. If you do:
>
> inst = A()
> inst.a = "bar"
>
> you don't modify inst.__a, unlike the following ruby code, which does
> modify @a .
>
> inst = A.new
> inst.a = "bar"

I understand. That's why I said it was a rough translation of the ruby
code. I was only trying to say that it's strange when learning ruby,
to get your head around the idea that instance (and class) variables
are not attributes; that all attributes are callable. The example was
merely to demonstrate the distinction between instance method and
instance variable in ruby. The python isn't supposed to have the exact
same behavior, just a similar semantic.

Regards,
Jordan



More information about the Python-list mailing list