【发布时间】:2016-09-27 06:45:01
【问题描述】:
我最近一直在玩 Ruby,但我似乎找不到我的问题的答案。
我有一个类和一个子类。类有一些initialize 方法,子类有自己的initialize 方法,该方法应该从它继承一些(但不是全部)变量,并将自己的变量添加到子类对象中。
我的Person 有@name、@age 和@occupation。
我的Viking 应该有一个@name 和@age,它继承自Person,另外还有一个@weapon,Person 没有。 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
问题是
-
这是设计使然,我想犯一些违反 OOP 原则的大罪吗?
-
我如何让它以我想要的方式工作(最好没有任何疯狂的复杂元编程技术等)?
【问题讨论】:
标签: ruby inheritance initialization