FEEDBACK WANTED: Type/class unification

Martin von Loewis loewis at informatik.hu-berlin.de
Tue Jul 31 07:52:06 EDT 2001


Guido van Rossum <guido at python.org> writes:

> Can you summarize what Ruby does?

By default, instance attributes are not accessible outside of instance
methods. In instance methods, attributes are denoted by an initial
ampersand (e.g. @age, @name, @counter). You can declare attributes as
accessible, using

  attr              :age
  attr_accessor     :name
  attr_writer       :counter

(where attr, attr_accessor, attr_write are methods, and :age is the
equivalent of Python's id('age')).

It appears that these methods only generate accessor functions, which
are denoted in the following way

class ADemo
  def initialize(name)
    @name = name
  end

  def name()
    return @name+ at name
  end

  def name=(newname)
    puts ("Assigning "+newname)
    @name = newname
  end
end

p = ADemo.new("Dave")
puts p.name
p.name = "Martin"
puts p.name

This defines a class ADemo, which sets an attribute @name in the
initializer. It also defines a read accessor, name(), and a write
accessor, name=. The output of this program is

DaveDave
Assigning Martin
MartinMartin

I may be wrong, but it seems that the interpreter is unaware that
these are actually accessor functions. Instead, it is allowed to omit
the parentheses in method calls in Ruby, i.e.

p.foo(1)

can also be written as

p.foo 1

In particular,

puts p.name

is really the same thing as 

Kernel.puts(p.name())

p.name cannot be mistaken for an attribute access, since attributes
are only accessible inside methods, where they are denoted as @name.

Likewise (but as a special case in the syntax),

p.name = "Martin"

is the same thing as

p.name=("Martin")

I.e. the parser does special-case the writer function, but only
insofar as to allow whitespace in the method name.

Regards,
Martin



More information about the Python-list mailing list