继承如何在Ruby中工作? [英] How does Inheritance work in Ruby?
问题描述
根据Dave Thomas在他关于Ruby对象模型的讨论,Ruby中没有类方法。方法的接收者是类对象还是实例对象之间只有区别。
According to Dave Thomas in his talk about the Ruby Object Model, there are no "class methods" in Ruby. There is only difference between whether the receiver of the method is a "class object" or an "instance object".
class Dave
def InstaceMethod ### will be stored in the current class (Dave)
puts "Hi"
end
class << self ### Creates an eigenclass, if not created before
def say_hello
puts "Hello"
end
end
end
默认情况下,祖先
方法不显示元类:
By default, ancestors
method doesn't show the metaclass:
class Dave
class << self
def metaclass ### A way to show the hidden eigenclass
class << self; self; end
end
end
end
p Dave.ancestors
# => [Dave, Object, Kernel, BasicObject]
p Dave.metaclass.ancestors
# => [Class, Module, Object, Kernel, BasicObject]
但是,我认为真正的那个会是某种东西喜欢:
However, I assume the real one would be something like:
# => [<eigenclass>, Class, Module, Object, Kernel, BasicObject]
p Dave.class.instance_method(false)
# => [:allocate, :new, :superclass]
p Dave.metaclass.instance_method(false)
# => [:say_hello, :metaclass]
现在是继承。
class B < Dave
end
p B.say_hello
# => "Hello"
p B.ancestors
# => [B, Dave, Object, Kernel, BasicObject]
p B.class.instance_methods(false)
# => [:allocate, :new, :superclass]
以下内容将为<$ c创建一个新的本征类$ c> B :
p B.metaclass.ancestors
# => [Class, Module, Object, Kernel, BasicObject]
p B.metaclass.instance_method(false)
# => []
-
如何
B.ancestors
和B.metaclass.ancestors
看起来像是否还包含了本征类?方法say_hello
存储在一个特征类中(我假设B.class
继承自)但是在哪里?
How would the
B.ancestors
andB.metaclass.ancestors
look like when the eigenclasses are also included? The methodsay_hello
is stored in an eigenclass, (which I assumeB.class
inherits from) but where is that?
由于有两个祖先链( B.ancestors
和 B。 class.ancestors
或 B.metaclass.ancestors
),实际上如何进行继承?
Since there are two ancestor chains (B.ancestors
and B.class.ancestors
or B.metaclass.ancestors
), how does the inheritance actually take place?
推荐答案
Eigenclass是一个偷偷摸摸的隐藏者。你已经通过开课成功地揭示了它。但它并不存在于普通阶级的祖先中。由于它是隐藏,因此您无法通过向特征类本身发送祖先
方法来查看它。继承树如下所示:
Eigenclass is a sneaky hidden one. You have successfully revealed it by opening class. But it does not exist in the ancestors of normal class. And since it is hidden, you cannot see it by sending ancestors
method to a eigenclass itself. The inheritance tree is like the following:
B ---S--> Dave ---S---> Object ---S---> BasicObject
| | | |
E E E E
| | | |
#B --S--> #Dave ---S---> #Object ---S---> #BasicObject --S---> Class,,Object,BasicObject
S
看台对于超类,而对于本征类, E
。
S
stands for superclass, while E
for eigenclass.
这篇关于继承如何在Ruby中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!