2016-07-07 65 views
1

我正在試圖製作一個像戰艦一樣的程序。基於輸入生成行和列()

這是我到目前爲止。

class Start: 
    def play(rows, columns): 
     for i in rows: 
      for j in columns: 
       print("O") 
print("Testing") 
rowinput = input("rows: ") 
colinput = input("columns: ") 
s = start() 
s.play(rowinput, colinput) 

這是錯誤代碼我得到:

Traceback (most recent call last): 
File "C:/Users/OfficeUser/Documents/battleship.py", line 12, in <module> 
s.play(rowinput, colinput) 
TypeError: play() takes 2 positional arguments but 3 were given 

我的問題是:如何通過input()實現基於用戶輸入的行和列的一代?

回答

2

類實例的方法將類的實例作爲第一個參數。

self加上play的定義。當你調用該方法的類實例被傳遞,所以你需要處理,在你的方法定義:

def play(self, rows, columns): 
    #... 

還有其他的bug等待去了,這樣的:你需要投你輸入int ,那麼你就需要在你的循環使用range

for i in range(rows): 
    for j in range(columns): 
     print("O") 
+0

當添加自我時,我得到了一個輸出「O」。 – kommander0000

+0

@ kommander0000你期待什麼輸出? –

+0

基於收集的輸入,可以說行= 6和列= 6,你會得到一個6x6的網格 – kommander0000

0

當你調用s.play(rowinput, colinput),對象「S」也傳遞(隱含的)的功能「玩」(因爲它是第一個參數)。這就是錯誤所說的三個參數正在傳遞給函數播放,但簽名表示它只接受兩個參數。現在在python中,約定是使用名稱「self」作爲類實例的參數。所以只需添加另一個參數的功能,就像這樣

def play(self, rows, columns): 
+0

添加自我時,我的輸出只是「O」 – kommander0000