在class delcaration之后设置类继承或在const_set类上设置类继承 [英] Set class inheritance after class delcaration OR setting class inheritance on const_set class

查看:112
本文介绍了在class delcaration之后设置类继承或在const_set类上设置类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果以前已经定义了一个类,我如何告诉它继承自一个类Parent

If a class has been previously defined how can I tell it to inherit from a class Parent

例如:

class Parent
  ..
end

class Klass
  ..
end

现在我想要继承自父母

我不能重新打开该类并设置它,因为我会得到一个类不匹配错误

I cant re-open the class and set it because I will get a class mismatch error

class Klass < Parent
  ..
end

具体来说,我试图找出如何通过Object.const_set

Specifically I am trying to find out how to set the class inheritance on a class im creating through Object.const_set

klass = Object.const_set('Klass', Class.new)

我如何告诉Klass继承自Parent类?

How can I tell Klass to inherit from class Parent?

推荐答案

没有办法更改已经存在的类的超类。

There is no way to change the superclass of an already existing class.

要指定超类您正在动态创建一个类,只需将超类作为参数传递给 Class.new

To specifiy the superclass of a class you're creating dynamically, you simply pass the superclass as an argument to Class.new.

class Parent
end
klass = Class.new(Parent)
klass.superclass #=> Parent

正如一个旁注:你不是用 const_set 。您正在使用 Class.new 创建它。您只需将创建的类存储在具有 const_set 的常量中。一旦 const_set 被调用, Class.new 已经发生,超类不能被更改。

Just as a side note: You're not creating the class with const_set. You're creating it with Class.new. You're simply storing the created class in a constant with const_set. Once const_set is invoked, Class.new has already happened and the superclass cannot be changed anymore.

这篇关于在class delcaration之后设置类继承或在const_set类上设置类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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