2013-10-17 97 views
0

在Python中,我可以做這樣的事情:的Python像Ruby繼承

# say.py 
class Speaker: 
    def speak(self,word): 
     pass 
    def Do(self): 
     self.speak("hello") 
Speaker().Do() 

如果我跑這一點,那就什麼也不做。我能做到這一點在其他模塊:

import say 
class Test(say.Speaker): 
    def speak(self,word): 
     print(word) 
Test().Do() 

如果我跑這一點,因爲我繼承了它,當我做在say.pyspeak功能被完全改寫:

class Test(say.Speaker) 

所以,當我運行該腳本,它會打印這個詞而不是無所事事。我希望腳本的名稱能夠動態更改文件名,而無需編輯say.rb

如果我跑say.py並做:

Speaker().do() 

什麼也不會發生,但是當我運行其他PY模塊,並將它做的事:

Test.Do() 

因爲我繼承了它,它被覆蓋,並改變了speak的功能。做Speaker().Do(),因爲它沒有做任何事情,但如果我做Test.Do(),它確實工作,因爲覆蓋。

他們是一個紅寶石的等價物,我在Python中做了什麼,如果是的話,我該怎麼做呢?

回答

2

它非常相似。這裏的 'say.rb':

module Say 
    class Speaker 
    def speak(word) end 
    def Do() speak("Hello") end 
    end 
end 

在你的其他模塊:

require 'say' 
class Test < Say::Speaker 
    def speak(word) 
    puts(word) 
    end 
end 

爲了證明:

Test.new.Do 
+0

謝謝你,這讓我很難相處,因爲你解決了我的問題。 – anakin

1

當然有。你有什麼嘗試,沒有奏效?請閱讀inheritance in Ruby

你只需要在Python中改變幾個字符就可以在Ruby中工作。

+0

謝謝您的回答。 – anakin