Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Ruby and Python versions of"self"?

I've done some Python but have just now starting to use Ruby
I could use a good explanation of the difference between "self" in these two languages.

Obvious on first glance:
Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.
Python methods receive self as an explicit argument, whereas Ruby does not.
Ruby sometimes has methods explicitly defined as part of self using dot notation.

Initial Googling reveals
http://rubylearning.com/satishtalim/ruby_self.html
http://www.ibiblio.org/g2swap/byteofpython/read/self.html

like image 278
John Mulder Avatar asked Oct 01 '08 22:10

John Mulder


2 Answers

Python is designed to support more than just object-oriented programming. Preserving the same interface between methods and functions lets the two styles interoperate more cleanly.

Ruby was built from the ground up to be object-oriented. Even the literals are objects (evaluate 1.class and you get Fixnum). The language was built such that self is a reserved keyword that returns the current instance wherever you are.

If you're inside an instance method of one of your class, self is a reference to said instance.

If you're in the definition of the class itself (not in a method), self is the class itself:

class C
  puts "I am a #{self}"
  def instance_method
    puts 'instance_method'
  end
  def self.class_method
    puts 'class_method'
  end
end

At class definition time, 'I am a C' will be printed.

The straight 'def' defines an instance method, whereas the 'def self.xxx' defines a class method.

c=C.new

c.instance_method
#=> instance_method
C.class_method
#=> class_method
like image 50
webmat Avatar answered Nov 15 '22 08:11

webmat


Despite webmat's claim, Guido wrote that explicit self is "not an implementation hack -- it is a semantic device".

The reason for explicit self in method definition signatures is semantic consistency. If you write

class C: def foo(self, x, y): ...

This really is the same as writing

class C: pass

def foo(self, x, y): ... C.foo = foo

This was an intentional design decision, not a result of introducing OO behaviour at a latter date.

Everything in Python -is- an object, including literals.

See also Why must 'self' be used explicitly in method definitions and calls?

like image 24
Matthew Trevor Avatar answered Nov 15 '22 07:11

Matthew Trevor