我有一个名为LibraryItem
的Ruby类。我希望这个类的每个实例都有一个属性数组。这个数组很长,看起来像这样
['title', 'authors', 'location', ...]
请注意,这些属性并不是真正的方法,只是LibraryItem
拥有的属性列表。
接下来,我想创建一个名为LibraryBook
的LibraryItem
子类,它有一个属性数组,其中包含LibraryItem
的所有属性,但还将包含更多属性。
最终,我需要LibraryItem
的几个子类,每个子类都有自己版本的数组@attributes
,但每个子类都添加到LibraryItem
的@attributes
中(例如,LibraryBook
、LibraryDVD
、LibraryMap
等)。
所以,这是我的尝试:
class LibraryItem < Object
class << self; attr_accessor :attributes; end
@attributes = ['title', 'authors', 'location',]
end
class LibraryBook < LibraryItem
@attributes.push('ISBN', 'pages')
end
这不起作用。我得到了错误
undefined method `push' for nil:NilClass
如果它能工作,我会想要这样的东西
puts LibraryItem.attributes
puts LibraryBook.attributes
输出
['title', 'authors', 'location']
['title', 'authors', 'location', 'ISBN', 'pages']
(2010年5月2日新增)一种解决方案是使@attributes
成为一个简单的实例变量,然后在initialize
方法中为LibraryBoot
添加新的属性(这是由demas在其中一个答案中提出的)。
虽然这肯定是可行的(事实上,这也是我一直在做的),但我对此并不满意,因为它不是最优的:为什么每次创建对象时都要构造这些不变的数组?
我真正想要的是类变量可以从父类继承,但在子类中更改时不会在父类中更改。
https://stackoverflow.com/questions/2752641
复制相似问题