类方法,实例方法,实例变量,类变量之间的区别? [英] difference between class method , instance method , instance variable , class variable?

查看:95
本文介绍了类方法,实例方法,实例变量,类变量之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习红宝石.我对类方法,实例方法,实例变量和类变量感到困惑.我在Google上搜索了很多,但没有得到任何澄清.任何帮助以及示例,将不胜感激.

I recently started learning ruby. I am confused between class methods, instance methods, instance variables, and class variables. I googled a lot, but I didn't get any clarification on those. Any help along with examples would be appreciated.

推荐答案

首先看一下该图:

您可以正确地说" obj 具有一种称为my_method()的方法",这意味着您可以调用obj.my_method().相比之下,您不应该说"MyClass有一个名为my_method()的方法."那会令人困惑,因为这意味着您可以像调用类方法一样调用MyClass.my_method().

You can rightly say that "obj has a method called my_method( )," meaning that you’re able to call obj.my_method(). By contrast, you shouldn’t say that "MyClass has a method named my_method()." That would be confusing, because it would imply that you’re able to call MyClass.my_method() as if it were a class method.

要消除歧义,您应该说my_method()是MyClass的实例方法(而不仅仅是方法"),这意味着它是在MyClass中定义的,实际上您需要一个实例MyClass来调用它.这是相同的方法,但是当您谈论类时,您将其称为实例方法,而当您谈论对象时,您仅将其称为方法.记住这种区别,在编写这样的内省代码时,您不会感到困惑:

To remove the ambiguity, you should say that my_method() is an instance method (not just "a method") of MyClass, meaning that it’s defined in MyClass, and you actually need an instance of MyClass to call it. It’s the same method, but when you talk about the class, you call it an instance method, and when you talk about the object, you simply call it a method. Remember this distinction, and you won’t get confused when writing introspective code like this:

String.instance_methods == "abc".methods # => true String.methods == "abc".methods # => false

对象的实例变量位于对象本身中,而对象的方法位于对象的类中.这就是为什么相同类的对象共享方法但不共享实例变量的原因.

an object’s instance variables live in the object itself, and an object’s methods live in the object’s class. That’s why objects of the same class share methods but don’t share instance variables.

这篇关于类方法,实例方法,实例变量,类变量之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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