且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类方法,实例方法,实例变量,类变量之间的区别?

更新时间:2023-12-02 19:46:10

首先看一下该图:

您可以正确地说" 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.