2013-01-15 77 views
0
這裏

是Ruby類我:無法覆蓋基類的方法在派生類

class MyBase 
    class << self 
    def static_method1 
     @@method1_var ||= "I'm a base static method1" 
    end 

    def static_method1=(value) 
     @@method1_var = value 
    end 

    def static_method2 
     @@method2_var ||= "I'm a base static method2" 
    end 

    def static_method2=(value) 
     @@method2_var = value 
    end 
    end 

    def method3 
    MyBase::static_method1 
    end 
end 

class MyChild1 < MyBase 
end 

class MyChild2 < MyBase 
    class << self 
    def static_method1 
     @@method1_var ||= "I'm a child static method1" 
    end 
    end 
end 

c1 = MyChild1.new 
puts c1.method3 #"I'm a base static method1" - correct 


c2 = MyChild2.new 
puts c2.method3 # "I'm a base static method1" - incorrect. I want to get "I'm a child static method1" 

我所知道的attr_accessor和模塊,而是因爲我想他們,我不能在這裏使用使用它們在MyBase class中給出默認值。我想在MyChild2中覆蓋MyBase.static_method1

回答

2

問題是method3始終顯式調用基類上的方法。將其更改爲:

def method3 
    self.class.static_method1 
end 

之後,請考慮不要使用@@

@@在ruby中是非常違反直覺的,很少意味着你認爲它的意思。

@@的問題在於它在繼承的類和基類中共享全部See this blog post for an explanation

+0

哈,我剛剛找到解決方案。你是對的! – Alexandre

+0

<< @@的問題是它在所有繼承的類和基類之間共享>>那麼我如何使用默認值呢? – Alexandre

+0

@Alexandre您仍然可以在類方法中使用實例變量,它們被稱爲*類實例變量*。 –