2011-07-22 32 views
0

我無法獲得兩個類互動。下面是我在哪裏導入文件youtest.py第一類的代碼:讓兩個類互動

from youtest import MyTest 

class RunIt(object): 

    def __init__(self): 
    self.__class__ = MyTest 

r = RunIt() 
r.iffit() 

我想通過這個類來運行類MyTest的(下面的代碼):當我運行這個

from sys import exit 

class MyTest(object): 

    def death(self): 
    exit 

    def iffit(self): 

    oh_no = raw_input(">") 

    print "What is your name?" 

    if oh_no == "john": 
    print "welcome john" 

    else: 
    print "game over" 
    return 'death' 

我得到如下:

文件「youtest.py」 19行 回報「死」 語法錯誤:外功能「迴歸」

希望這個問題很清楚,謝謝你的幫助。

+1

當我在這裏查看所有問題後,我強烈建議閱讀[教程](http://docs.python.org/tutorial)。 – pillmuncher

+0

就可以了。 thnx多 –

回答

0

在Python中,這不是如何繼承的。

from youtest import MyTest 

class RunIt(MyTest): pass 

r = RunIt() 
r.iffit() 

雖然在這個例子中r = MyTest()會正常工作。您的SyntaxError是由您濫用空格引發的。每個縮進級別使用四個空格,就像Python中的標準一樣,所以您可以清楚地看到事物的組織結構。

你有另一個問題:return 'death'不會調用death,你需要return death()如果這就是你想要的。

最後,death()不會對exit做任何事情,只要引用它即可。你需要做exit()

2

print "What is your name?"開始的行不能正確縮進。在python中,空格非常重要。