我需要一些幫助將類屬性size
更改爲實例屬性。 這是當前代碼(工作):如何將類屬性更改爲實例屬性Python編程
class BoardHandler:
size=None
def __init__ (self):
self.board = None
if BoardHandler.size is None:
self.ask_size()
self.getNewBoard()
def ask_size(self):
while True:
try:
BoardHandler.size = int(input("Which size would you want? "))
break
except ValueError:
print("Wrong! try again")
當我嘗試改變類爲實例屬性是這樣的:
class BoardHandler:
def __init__ (self):
self.board = None
self.size = self.ask_size()
self.getNewBoard()
def ask_size(self):
while True:
try:
self.size = int(input("Which size would you want? "))
break
except ValueError:
print("Wrong! try again")
從現在開始
所以,而不是調用到size
與BoardHandler .size我呼籲self.size。但我得到的錯誤是:
Traceback (most recent call last):
File "/Users//Desktop/REVERSI/.py", line 281, in <module>
menu()
File "/Users//Desktop/REVERSI/.py", line 213, in meny
main1v1()
File "/Users//Desktop/REVERSI/.py", line 236, in main1v1
handler = BoardHandler()
File "/Users//Desktop/REVERSI/.py", line 35, in __init__
self.newBoard()
File "/Users//Desktop/REVERSI/.py", line 50, in newBoard
for i in range(self.size):
TypeError: 'NoneType' object cannot be interpreted as an integer
'ask_size'返回'無'。要麼返回一個int或只是調用'ask_size' –
你的意思是我會調用'self.ask_size'而不是'self.size'? @tmadam – Entropy
我的意思是調用'ask_size',但不要將它分配給'size'或讓'ask_size'返回一個int,就像@Daniel Sanchez的回答 –