局部变量,实例变量和类变量之间有什么区别? [英] What is the difference between local, instance, and class variables?
问题描述
可能重复:
类变量和类实例变量之间的区别?
Possible Duplicate:
Difference between class variables and class instance variables?
在读一本Ruby书的时候,我似乎错过了变量一章.现在,我似乎无法理解以下内容:
While reading a Ruby book, I seem to have missed the variables chapter. Now I can't seem to understand the following things:
- 什么是实例变量?
- 什么是类实例变量?
-
variable
,@instance_var
和@class_instance_var
有什么区别?
- What is an instance variable?
- What is a class instance variable?
- What is the difference between a
variable
,@instance_var
and@class_instance_var
?
我尝试阅读不同博客中的一些帖子,但我仍然不明白.任何帮助将不胜感激.
I tried to read some posts in different blogs, but I still do not understand. Any help would be appreciated.
推荐答案
什么是实例变量?
What is an instance variable?
这是一个具有与该类实例有关的独立值的变量.例如,一个Person
类可以将@name
和@age
作为实例变量. Person
的所有实例都有名称和年龄,但是对于这些实例,每个实例将具有不同的值.
It's a variable that has an idependant value that pertains to this instance of a class. For example, a Person
class could have @name
and @age
as instance variables. All instance of Person
have a name and age, but each instance will have a different value for those things.
什么是类实例变量?
What is a class instance variable?
这有点奇怪,但是您必须意识到Person
类本身是Class
的实例.因此它也可以具有实例变量.这通常用于配置类.可能要向类添加API密钥,以便可以使用该数据创建所有实例.
This is a little wierd, but you have to realize that the Person
class is itself an instance of Class
. So it too can have instance variables. This is often used to configure a class. Like perhaps to add an API key to a class so that all instance can be created with that data.
class PersonFetcher
# class method can set class instance variables
def self.set_api_key(key)
@api_key = key
end
# instance method sets instance variables
def set_name(name)
@name = name
end
end
@instance_var和@class_instance_var变量有什么区别?
What is the difference between a variable, @instance_var and @class_instance_var?
它如何持续.
variable
是本地的.它只是对对象的引用.一旦没有代码或对象引用此值,则将通过垃圾回收将其销毁.如果您继续使用它,它只会持续存在.
variable
is local. It's simply a reference to an object. Once no code or object has a reference to this value it is destroyed via garbage collection. It only persists if you keep using it.
@instance_var
在实例上保留.只要实例持久存在,它所拥有的实例变量也将保持不变.只要Person
实例存在,该实例将具有@name
.
@instance_var
persists on an instance. So long as the instance persists, the instance variables it has will as well. So long as the Person
instance exists, that instance will have a @name
.
@class_instance_var
保留在类对象上(记住该对象是Class
的实例).因此,它将永远存在于类对象中,因为您永远无法真正摆脱已声明的类.
@class_instance_var
persists on the class object (which remember is an instance of Class
). So it will exist in the class object forever, since you can never really get rid of declared classes.
这篇关于局部变量,实例变量和类变量之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!