gpt4 book ai didi

Ruby - 仅使用某些参数初始化继承, super ?

转载 作者:数据小太阳 更新时间:2023-10-29 07:43:52 25 4
gpt4 key购买 nike

最近我一直在研究 Ruby,但我似乎找不到问题的答案。

我有一个类和一个子类。类有一些 initialize 方法,子类有自己的 initialize 方法,应该从它继承一些(但不是全部)变量,并另外将自己的变量添加到子类对象。

我的@name@age@occupation

我的 Viking 应该有一个 @name@age 它继承自 Person,并且另外还有 @weaponPerson 没有。 Viking 显然不需要任何 @occupation,也不应该有。

# doesn't work
class Person
def initialize(name, age, occupation)
@name = name
@age = age
@occupation = occupation
end
end

class Viking < Person
def initialize(name, age, weapon)
super(name, age) # this seems to cause error
@weapon = weapon
end
end

eric = Viking.new("Eric", 24, 'broadsword')
# ArgError: wrong number of arguments (2 for 3)

您可以通过以下方式使其工作,但这两种解决方案都不吸引我

class Person
def initialize(name, age, occupation = 'bug hunter')
@name = name
@age = age
@occupation = occupation
end
end

class Viking < Person
def initialize(name, age, weapon)
super(name, age)
@weapon = weapon
end
end

eric = Viking.new("Eric", 24, 'broadsword')
# Eric now has an additional @occupation var from superclass initialize


class Person
def initialize(name, age, occupation)
@name = name
@age = age
@occupation = occupation
end
end

class Viking < Person
def initialize(name, age, occupation, weapon)
super(name, age, occupation)
@weapon = weapon
end
end

eric = Viking.new("Eric", 24, 'pillager', 'broadsword')
# eric is now a pillager, but I don't want a Viking to have any @occupation

问题是

  1. 这是设计使然,我想犯下一些违反 OOP 原则的大罪吗?

  2. 如何让它按照我想要的方式工作(最好没有任何疯狂复杂的元编程技术等)?

最佳答案

super 如何处理参数

关于参数处理,super 关键字可以以三种方式表现:

当不带参数调用时,super 会自动将调用它的方法(在子类中)接收到的任何参数传递给父类(super class)中的相应方法。

class A
def some_method(*args)
puts "Received arguments: #{args}"
end
end

class B < A
def some_method(*args)
super
end
end

b = B.new
b.some_method("foo", "bar") # Output: Received arguments: ["foo", "bar"]

如果使用空括号(空参数列表)调用,则不会将任何参数传递给父类(super class)中的相应方法,无论调用父类(super class)的方法(在子类上)是否接收到任何参数。

class A
def some_method(*args)
puts "Received arguments: #{args}"
end
end

class B < A
def some_method(*args)
super() # Notice the empty parentheses here
end
end

b = B.new
b.some_method("foo", "bar") # Output: Received arguments: [ ]

当使用显式参数列表调用时,它会将这些参数发送到父类(super class)中的相应方法,而不管调用父类(super class)的方法(在子类上)是否收到任何参数。

class A
def some_method(*args)
puts "Received arguments: #{args}"
end
end

class B < A
def some_method(*args)
super("baz", "qux") # Notice that specific arguments were passed here
end
end

b = B.new
b.some_method("foo", "bar") # Output: Received arguments: ["baz", "qux"]

关于Ruby - 仅使用某些参数初始化继承, super ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37508685/

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