Ruby 关于父类中引用子类实例变量,看代码会不会有点奇怪?

yakczh · July 13, 2015 · Last by yakczh replied at July 13, 2015 · 1454 hits
class Model
  def initialize()   
       puts "Model initialize\n"
  end

  def see
       puts " table is  " + @table
  end

  def add(u)
       puts "insert into " + @table+ "values " +u
   end

end
-------------------------------------------
class User < Model
  def initialize    
     @table='user'  
     puts "User Initalize"
  end  

  def log
     print @table
   end
end


a=User.new
a.see
u="xxx"
a.add(u)
a.log

如果只看父类,会不会觉得这个@table变量不知道是从哪冒出来的

是不妥当的。如果 parent 不需要@table, 那么#see 和#add 不需要定义在 parent 里面。如果需要,那 parent 需要自己定义@table, 否则本身都不可用。

#1 楼 @billy parent 需要 parent 中需要封装所有子类共同的操作,但是实际参数只有子类才能提供

#3 楼 @nouse 那应该怎么写才对?

You need to Sign in before reply, if you don't have an account, please Sign up first.