2013-10-17 119 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