实例变量继承 [英] Instance Variables Inheritance

查看:131
本文介绍了实例变量继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一个类如何访问其超类的实例变量以及它不是如何继承的?我在谈论'Ruby编程语言'和示例

Can someone explain how a class can access the instance variables of its superclass and how that is not inheritance? I'm talking about 'The Ruby Programming Language' and the example

class Point
  def initialize(x,y) # Initialize method 
     @x,@y = x, y      # Sets initial values for instance variables
  end

end

class Point3D < Point
 def initialize(x,y,z)
   super(x,y)
   @z = z
 end
 def to_s
   "(#@x, #@y, #@z)"  # Variables @x and @y inherited?
 end
end

Point3D.new(1,2,3).to_s => "(1, 2, 3)"

如何上课 Point3D to_s 内访问 x y 如果他们没有继承?该书说:

How can class Point3D access x and y inside to_s if they're not inherited? The book says:


它们有时似乎是继承的原因是实例变量是由首先赋值的方法创建的他们,这些方法经常被继承或链接。

"The reason that they sometimes appear to be inherited is that instance variables are created by the methods that first assign values to them, and those methods are often inherited or chained."

但我无法弄清楚它的真正含义。

but I can't figure out what it really means.

推荐答案

你是对的,这本书是错的,或者至少措辞不好






我认为这本书完全错了,或者充其量,这是一个非常混乱的解释。

You are right, the book is wrong, or at least poorly worded


I would argue that the book is simply wrong, or at best, it's making a quite muddy explanation.

所有OO语言,超类和派生类没有单独的对象。当您创建派生类的实例时,也是超类的实例。有一个对象,它同时是两个类。

In all OO languages, the superclass and derived class don't have separate objects. When you create an instance of the derived class, it is also an instance of the superclass. There is one object and it is both classes at once.

由于只有一个对象,因此只有一组实例变量。

Since there is only one object, there is only one set of instance variables.

这与所有其他OO系统相同。本书关于如何运行哪个方法以及方法本身如何实际继承的奇怪论证并没有增加太多的清晰度。

This is the same as all other OO systems. The weird argument that book makes about how it just matters which method is run and how the methods themselves are what are really inherited does not add much in the way of clarity.

术语的问题是,当然,在动态类型系统中,首先没有声明,因此子类的定义肯定不会继承任何字段声明......因为当然没有任何声明。但是,因为没有类型可以继承不会使相反的语句(实例变量不被继承)更加真实,并且它会增加相当多的混淆,因为它暗示父母会以某种方式使不同实例变量,这是尝试以他们的方式谈论对象的荒谬结果。

The problem with the terminology is that, sure, in a dynamically typed system there is no declaration in the first place, and so certainly the definition of the subclass doesn't inherit any field declarations ... because of course there aren't any. But just because there are no types to inherit doesn't make the opposite statement ("instance variables are not inherited") any more true, and it adds quite a bit of confusion because it implies that somehow the parent would have different instance variables, which is the nonsensical result of trying to talk about the objects the way they do.

这篇关于实例变量继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆