Ruby 和 Python 版本的“self"有什么区别? [英] What is the difference between Ruby and Python versions of"self"?

查看:44
本文介绍了Ruby 和 Python 版本的“self"有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做过一些 Python,但现在才开始使用 Ruby
我可以很好地解释这两种语言中自我"之间的区别.

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.

乍一看很明显:
Self 不是 Python 中的关键字,但无论你怎么称呼它,都有一个self-like"值.
Python 方法接收 self 作为显式参数,而 Ruby 没有.
Ruby 有时使用点表示法将方法明确定义为 self 的一部分.

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.

最初的谷歌搜索显示
http://rubylearning.com/satishtalim/ruby_self.html
http://www.ibiblio.org/g2swap/byteofpython/read/self.html

推荐答案

Python 旨在支持的不仅仅是面向对象的编程.在方法和函数之间保留相同的接口可以让两种风格更干净地互操作.

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 从头开始​​构建为面向对象.甚至文字也是对象(评估 1.class 并获得 Fixnum).该语言的构建使得 self 是一个保留关键字,无论您身在何处,它都会返回当前实例.

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.

如果您在某个类的实例方法中,则 self 是对所述实例的引用.

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

如果您在类本身的定义中(而不是在方法中),则 self 是类本身:

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

在类定义时,将打印I am a C".

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

直接的'def'定义了一个实例方法,而'def self.xxx'定义了一个类方法.

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

这篇关于Ruby 和 Python 版本的“self"有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆