Ruby 从子类对象创建对象
假设我有两门课:Ruby 从子类对象创建对象,ruby,oop,Ruby,Oop,假设我有两门课: Class Foo attr_accessor :bar end Class Baz < Foo end 怎么做 Baz的实例,其中包含Foo实例的数据 由于构造函数已经接受属性作为散列,因此可以创建一个方法以将Foo的属性作为散列返回: class Foo attr_accessor :bar def initialize(attributes={}) @bar = attributes[:bar] end def attribu
Class Foo
attr_accessor :bar
end
Class Baz < Foo
end
怎么做
Baz
的实例,其中包含Foo
实例的数据
由于构造函数已经接受属性作为散列,因此可以创建一个方法以将Foo
的属性作为散列返回:
class Foo
attr_accessor :bar
def initialize(attributes={})
@bar = attributes[:bar]
end
def attributes
{:bar => bar}
end
end
class Baz < Foo
end
为什么不直接创建
Baz
的实例呢?既然Baz
是Foo
,我不明白为什么需要引用这两种类型。忽略我的示例代码,通常可以从子类对象创建对象,还是必须编写类似Baz.create\u from\u Foo(Foo)的类方法
?甚至“从子类对象创建对象”都意味着什么???一个子类对象已经是超类的一个实例,从一个子类“创建”一个超类是bass ackwards。我认为OP将继承与合成混淆了,这是一个很好的解决方案。警告:如果设置Foo.new(:bar=>Array.new)
或其他对象,然后设置Baz.new
,两者都将引用完全相同的数组。意思是,在f.bar
中添加一些东西会改变b.bar
@CharlesCaldwell没错,f.bar.upcase代码>也会影响b.bar
(它是同一个对象)。如果不需要,构造函数/设置器必须复制对象。
class Foo
attr_accessor :bar
def initialize(attributes={})
@bar = attributes[:bar]
end
def attributes
{:bar => bar}
end
end
class Baz < Foo
end
f = Foo.new(:bar => "Hi World") #=> #<Foo:0x007fd09a8614c0 @bar="Hi World">
f.attributes #=> {:bar=>"Hi World"}
b = Baz.new(f.attributes) #=> #<Baz:0x007fd09a861268 @bar="Hi World">