您的位置:宽带测速网 > 编程知识 > Ruby类变量如何实现继承

Ruby类变量如何实现继承

2025-07-04 09:58来源:互联网 [ ]

在Ruby中,类变量不是继承的。类变量是在类定义中声明的变量,它们属于类本身而不是类的实例。当一个类继承另一个类时,子类会继承父类的类变量,但这些变量与实例变量不同,它们不会被子类的实例共享。

如果你想要在子类中修改父类的类变量,你可以使用superclass方法来访问父类,并直接修改父类的类变量。这里有一个例子:

class Parent@@class_variable = "I am a class variable in Parent"endclass Child < Parentdef modify_parent_class_variableParent.class_eval do@@class_variable = "I am a modified class variable in Parent"endendendchild = Child.newputs child.class_variable # 输出 "I am a modified class variable in Parent"

在这个例子中,我们首先定义了一个名为Parent的类,其中包含一个类变量@@class_variable。然后,我们创建了一个名为Child的子类,它继承了Parent类。在Child类中,我们定义了一个名为modify_parent_class_variable的方法,该方法使用Parent.class_eval来修改父类的类变量。当我们创建一个Child类的实例并调用modify_parent_class_variable方法时,我们可以看到父类的类变量已经被修改。