我有几个继承自单个类的类。每个子类创建一些数据结构,然后父类对该数据执行操作。
问题:无论对象是否已实例化,如何让父类使用该数据。
class A
def self.static_test
puts @myvar + "_static"
end
def instantiated_test
puts @myvar + "_instantiated"
end
end
class B<A
@myvar = "this works B"
end
class C<A
@myvar = "this works C"
end
B.static_test
B.new.instantiated_test
C.static_test
C.new.instantiated_test
B.static_test
B.new.instantiated_test
我需要上面的代码来打印:
this works B_static this works B_instantiated this works C_static this works C_instantiated this works B_static this works B_instantiated
我使用的是Ruby 1.8.7。
编辑:看起来我的原始问题有点令人困惑。我需要静态和实例化方法来使用相同的数据。但是这些方法不会做同样的事情。我更新了示例代码以反映这一点。
答案 0 :(得分:3)
def instantiated_test
self.class.static_test
end
顺便说一句,如果您确定继承的类具有某种结构,请将其提取到父类。如果您不确定,请不要在父类中使用它。家长的实施不应该取决于孩子的实施。
答案 1 :(得分:1)
class A
class << self
attr_reader :myvar
end
# Alternatively:
# def self.myvar; @myvar; end
def self.static_test
puts myvar
end
def instantiated_test
puts self.class.myvar
end
end
class B<A
@myvar = "this works B"
end
class C<A
@myvar = "this works C"
end
B.static_test
#=> this works B
B.new.instantiated_test
#=> this works B
C.static_test
#=>this works C
C.new.instantiated_test
#=>this works C
B.static_test
#=> this works B
B.new.instantiated_test
#=> this works B
答案 2 :(得分:0)
class A
def self.static_test
puts @myvar
end
def instantiated_test
puts @myvar
end
end
class B<A
@myvar = "this works B"
@@myvar = @myvar
def initialize
@myvar = @@myvar
end
end
class C<A
@myvar = "this works C"
@@myvar = @myvar
def initialize
@myvar = @@myvar
end
end
但这很难看,需要重复。