gpt4 book ai didi

ruby - 调用父类的初始化函数?

转载 作者:行者123 更新时间:2023-12-01 22:34:20 25 4
gpt4 key购买 nike

我对 Ruby 没有多少经验,而且我来自 C++,其中通常使用初始化列表。关于 Ruby,我想知道的一件事如下:

给定以下类 Vehicle 及其子类 Car:

class Vehicle
attr_reader :wheels
def initialize(wheels)
@wheels = wheels
end
end

class Car < Vehicle
def initialize(car_stuff)
@wheels = 4 # this is the part I don't like! ;)
@car_stuff = car_stuff
end
end

有没有一种方法可以调用父类(super class)的构造方法,而不用遍历 Vehicle 类可能具有的不同变量?

提前致谢。

最佳答案

这就是 super 的用途:

class Car < Vehicle
def initialize(car_stuff)
super(4)
@car_stuff = car_stuff
end
end

关于ruby - 调用父类的初始化函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26973290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com