Ruby类和实例变量跨继承生命周期演示
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ruby类和实例变量跨继承生命周期演示相关的知识,希望对你有一定的参考价值。
require 'logger' $log = Logger.new(STDOUT) $log.level = Logger::INFO $log.progname = "LifecycleDemo" $log.formatter = proc { |severity, datetime, progname, msg| #"#{datetime.strftime("%Y-%b-%d %a %H:%M")} #{severity} #{progname} {#{msg}} " "#{msg} " } #$log.datetime_format = "%a %Y-%m-%d %H:%M" class FirstClass @@grandClass = "FirstClassVar" # class level variable to track def initialize @grandVar = "FirstInstanceVar" # instance variable to track $log.info("! FirstClass init, #{ids}") end def grand $log.info("> FirstClass grand, #{ids}") end def ids "#{self.class.name}:: #{@@grandClass}:#{@@grandClass.object_id}, #{@grandVar}:#{@grandVar.object_id}" end end class SecondClass < FirstClass def initialize @ego_hilite = "-" * 15 super $log.info("! Second class init, #{ids}") end def spill_it $log.info("> Spill It call, #{ids}") end def alter_ego @grandVar = "SecondInstanceVar" @@grandClass = "SecondClassVar" $log.info(" #{@ego_hilite} Ego altered by the #{self.class.name} #{@ego_hilite} ") end end class ThirdClass < SecondClass @@grandClass = "ThirdClassStatic" def initialize super $log.info("! 3rd class init, #{ids}") end def alter_ego @grandVar = "ThirdInstanceVar" @@grandClass = "ThirdClassVar" $log.info(" #{@ego_hilite} Ego altered by the Third Class #{@ego_hilite} ") end end def test(instance) hilite = "*" * 20 $log.info(" #{hilite} Testing instance of #{instance.class.name} BEGIN #{hilite}") instance.grand instance.spill_it # see what gets changed if anything: instance.alter_ego instance.grand instance.spill_it $log.info(" #{hilite} Testing instance of #{instance.class.name} END #{hilite}") end test(SecondClass.new) test(ThirdClass.new)
以上是关于Ruby类和实例变量跨继承生命周期演示的主要内容,如果未能解决你的问题,请参考以下文章