类变量和类实例变量之间的区别?
谁能告诉我类变量和类实例变量之间的区别?
Can anyone tell me about the difference between class variables and class instance variables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
谁能告诉我类变量和类实例变量之间的区别?
Can anyone tell me about the difference between class variables and class instance variables?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
类变量 (
@@
) 在该类及其所有后代之间共享。类实例变量 (@
) 不被该类的后代共享。类变量 (
@@
)让我们有一个带有类变量
@@i
的类 Foo,以及用于读取和写入@ 的访问器@i
:还有一个派生类:
我们看到 Foo 和 Bar 对于
@@i
具有相同的值:并且更改
@@i
会改变它在两者中:类实例变量 (
@
)让我们创建一个简单的类,其中包含类实例变量
@i
和用于读写的访问器>@i
:还有一个派生类:
我们看到虽然Bar继承了
@i
的访问器,但它并没有继承@i
本身:我们可以设置Bar 的
@i
而不影响 Foo 的@i
:A class variable (
@@
) is shared among the class and all of its descendants. A class instance variable (@
) is not shared by the class's descendants.Class variable (
@@
)Let's have a class Foo with a class variable
@@i
, and accessors for reading and writing@@i
:And a derived class:
We see that Foo and Bar have the same value for
@@i
:And changing
@@i
in one changes it in both:Class instance variable (
@
)Let's make a simple class with a class instance variable
@i
and accessors for reading and writing@i
:And a derived class:
We see that although Bar inherits the accessors for
@i
, it does not inherit@i
itself:We can set Bar's
@i
without affecting Foo's@i
:首先,您必须了解类也是实例——
Class
类的实例。一旦理解了这一点,您就可以理解类可以像常规(读取:非类)对象一样具有与其关联的实例变量。
请注意,
Hello
上的实例变量与Hello
的实例上的实例变量完全无关且不同。类变量<另一方面, /strong> 是上述两者的一种组合,因为它可以在
Hello
本身及其实例上以及Hello
的子类及其实例上访问。实例:由于上述奇怪的行为,许多人说要避免使用类变量,而建议使用类实例变量。
First you must understand that classes are instances too -- instances of the
Class
class.Once you understand that, you can understand that a class can have instance variables associated with it just as a regular (read: non-class) object can.
Note that an instance variable on
Hello
is completely unrelated to and distinct from an instance variable on an instance ofHello
A class variable on the other hand is a kind of combination of the above two, as it accessible on
Hello
itself and its instances, as well as on subclasses ofHello
and their instances:Many people say to avoid
class variables
because of the strange behaviour above, and recommend the use ofclass instance variables
instead.另外我想补充一点,您可以从类的任何实例访问类变量(
@@
),但是您不能对类实例变量(
@< /代码>)
Also I want to add that you can get access to the class variable (
@@
) from any instance of the classBut you can't do the same for the class instance variable(
@
)