猿问
下载APP

类变量和类实例变量之间的区别?

类变量和类实例变量之间的区别?

谁能告诉我类变量和类实例变量之间的区别?



慕仰8121524
浏览 56回答 3
3回答

三国纷争

类变量(@@)在类及其所有后代之间共享。@类的后代不共享类实例变量()。类变量(@@)让我们有一个带有类变量的类Foo @@i,以及用于读写的访问器@@i:class Foo&nbsp; @@i = 1&nbsp; def self.i&nbsp; &nbsp; @@i&nbsp; end&nbsp; def self.i=(value)&nbsp; &nbsp; @@i = value&nbsp; endend派生类:class Bar < Fooend我们看到Foo和Bar具有相同的值@@i:p Foo.i&nbsp; &nbsp; # => 1p Bar.i&nbsp; &nbsp; # => 1改变@@i一个改变它们:Bar.i = 2p Foo.i&nbsp; &nbsp; # => 2p Bar.i&nbsp; &nbsp; # => 2类实例变量(@)让我们创建一个带有类实例变量的简单类@i和用于读写的访问器@i:class Foo&nbsp; @i = 1&nbsp; def self.i&nbsp; &nbsp; @i&nbsp; end&nbsp; def self.i=(value)&nbsp; &nbsp; @i = value&nbsp; endend派生类:class Bar < Fooend我们看到虽然Bar继承了访问器@i,但它不会继承@i自己:p Foo.i&nbsp; &nbsp; # => 1p Bar.i&nbsp; &nbsp; # => nil我们可以在@i不影响Foo的情况下设置Bar @i:Bar.i = 2p Foo.i&nbsp; &nbsp; # => 1p Bar.i&nbsp; &nbsp; # => 2

幕布斯7119047

首先,您必须了解类也是实例 - 类的实例Class。一旦理解了这一点,就可以理解一个类可以将实例变量与它相关联,就像常规(读取:非类)对象一样。Hello&nbsp;=&nbsp;Class.new#&nbsp;setting&nbsp;an&nbsp;instance&nbsp;variable&nbsp;on&nbsp;the&nbsp;Hello&nbsp;classHello.instance_variable_set(:@var,&nbsp;"good&nbsp;morning!")#&nbsp;getting&nbsp;an&nbsp;instance&nbsp;variable&nbsp;on&nbsp;the&nbsp;Hello&nbsp;classHello.instance_variable_get(:@var)&nbsp;#=>&nbsp;"good&nbsp;morning!"请注意,在一个实例变量Hello是完全无关的且不同于一个实例变量上的实例的Hellohello&nbsp;=&nbsp;Hello.new#&nbsp;setting&nbsp;an&nbsp;instance&nbsp;variable&nbsp;on&nbsp;an&nbsp;instance&nbsp;of&nbsp;Hellohello.instance_variable_set(:@var,&nbsp;:"bad&nbsp;evening!")#&nbsp;getting&nbsp;an&nbsp;instance&nbsp;variable&nbsp;on&nbsp;an&nbsp;instance&nbsp;of&nbsp;Hellohello.instance_variable_get(:@var)&nbsp;#=>&nbsp;"bad&nbsp;evening!")#&nbsp;see&nbsp;that&nbsp;it's&nbsp;distinct&nbsp;from&nbsp;@var&nbsp;on&nbsp;HelloHello.instance_variable_get(:@var)&nbsp;#=>&nbsp;"good&nbsp;morning!"一类变量,另一方面是一种以上两者的结合,因为它可以访问Hello本身及其实例,以及在子类Hello和它们的实例:HelloChild&nbsp;=&nbsp;Class.new(Hello)Hello.class_variable_set(:@@class_var,&nbsp;"strange&nbsp;day!")hello&nbsp;=&nbsp;Hello.new hello_child&nbsp;=&nbsp;HelloChild.newHello.class_variable_get(:@@class_var)&nbsp;#=>&nbsp;"strange&nbsp;day!"HelloChild.class_variable_get(:@@class_var)&nbsp;#=>&nbsp;"strange&nbsp;day!"hello.singleton_class.class_variable_get(:@@class_var)&nbsp;#=>&nbsp;"strange&nbsp;day!"hello_child.singleton_class.class_variable_get(:@@class_Var)&nbsp;#=>&nbsp;"strange&nbsp;day!"很多人说要避免class variables因为上面的奇怪行为,而建议使用class instance variables代替。

芜湖不芜

另外我想补充一点,你可以从类的@@任何实例访问类变量()class Foo&nbsp; def set_name&nbsp; &nbsp; @@name = 'Nik'&nbsp; end&nbsp; def get_name&nbsp; &nbsp; @@name&nbsp; endenda = Foo.newa.set_namep a.get_name # => Nikb = Foo.newp b.get_name # => Nik但你不能对类实例变量(@)做同样的事情class Foo&nbsp; def set_name&nbsp; &nbsp; @name = 'Nik'&nbsp; end&nbsp; def get_name&nbsp; &nbsp; @name&nbsp; endenda = Foo.newa.set_namep a.get_name # => Nikb = Foo.newp b.get_name # => nil
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答