我在这里搜索了这个问题的答案,但找不到我想要的(确切地说),所以我会有点贪心,并向社区请求一些时间。我希望我的问题尽可能适用。
所以,在某些情况下,上周我一直在努力解决类、类变量和方法的概念,但在过去的两天里,我的理解取得了重大进展。但是,现在我面临着继承问题,无法弄清楚为什么在我可以继承而不使用它的情况下会使用 super。
例如:
class Animal
def initialize (type, breed, age)
@type = type
@breed = breed
@age = age
end
end
class Dog < Animal
end
class Cat < Animal
end
class Fish
end
woof = Dog.new("dog", "shitzu", 12)
meow = Cat.new("cat", "tabby", 5)
fish = Fish.new("fish", "gold", 2)
Output:
=> #<Dog:0x00000001447680 @type="dog", @breed="shitzu", @age=12>
=> #<Cat:0x0000000140c918 @type="cat", @breed="tabby", @age=5>
ArgumentError: wrong number of arguments (given 3, expected 0)
如您所见,我已经能够在我的 Dog 和 Cat 类上继承 Animal,我将它们标记为继承,但是在我的 Fish 上我无法继承,因为我没有继承。
如果有人能解释为什么我们使用 super,并指出我理解中的缺陷,我将不胜感激,我知道我可能完全误解了这里的用法,但我想澄清一下。感谢您的宝贵时间,感谢您的帮助。
最佳答案
使用 super
可以让类覆盖它从父类继承的方法并自定义它。
例如,在您的示例中,Dog
和 Cat
从 Animal
继承了 #initialize
- 但是如果我们想要 Dog
的一些特殊逻辑吗?
class Dog < Animal
def initialize(type, breed, age)
raise "Sorry, dogs don't live that long!" if age > 100
# Everything looks good - let Animal#initialize run now
super
end
end
这让 Dog
可以自定义其初始化方法的作用,但仍会调用原始的继承方法。
关于ruby - 当我可以继承而不使用它时,为什么我们在 ruby 中使用 super?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39692720/