(Python)为什么';当我在类定义之后调用方法对象时,它是否执行?
当我尝试在空闲状态下运行我的程序时(我目前使用的文本编辑器,notepad++说缩进错误,我不知道为什么),它只执行(Python)为什么';当我在类定义之后调用方法对象时,它是否执行?,python,class,function,object,methods,Python,Class,Function,Object,Methods,当我尝试在空闲状态下运行我的程序时(我目前使用的文本编辑器,notepad++说缩进错误,我不知道为什么),它只执行\uuuuuu init\uuuuu中的代码,这表明它已被创建为对象。但是在那之后,我试着使用main方法,但它什么也没做。我也换了一种不同的方法,但也没用。以下是我的节目: import sys class Main: def __init__(self): WinX = False WinO = False Turn =
\uuuuuu init\uuuuu
中的代码,这表明它已被创建为对象。但是在那之后,我试着使用main方法,但它什么也没做。我也换了一种不同的方法,但也没用。以下是我的节目:
import sys
class Main:
def __init__(self):
WinX = False
WinO = False
Turn = 'X'
LastTurn = 'X'
a, b, c, d, e, f, g, h, i = ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
PosList = []
PosList.append(a)
PosList.append(b)
PosList.append(c)
PosList.append(d)
PosList.append(e)
PosList.append(f)
PosList.append(g)
PosList.append(h)
PosList.append(i)
self.board = '+---+---+---+\n| ' + PosList[0] +' | '+ PosList[1] +' | '+ PosList[2] +' |\n+---+---+---+\n| '+ PosList[3] +' | '+ PosList[4] +' | '+ PosList[5] +' |\n+---+---+---+\n| '+ PosList[6] +' | '+ PosList[7] +' | '+ PosList[8] +' |\n+---+---+---+'
print self.board
def UpdateTurn(self):
if LastTurn == 'X':
Turn == 'O'
elif LastTurn == 'O':
Turn == 'X'
LastTurn = Turn
def WinChecker(self):
if a and b and c == 'X' or a and d and g == 'X' or a and e and i == 'X' or g and e and c == 'X' or g and h and i == 'X' or c and f and i == 'X':
WinX = True
if a and b and c == 'O' or a and d and g == 'O' or a and e and i == 'O' or g and e and c == 'O' or g and h and i == 'O' or c and f and i == 'O':
WinO = True
def UpdateBoard(self):
print self.board
def Starter(self):
while True:
try:
i = int(input(''))
except TypeError:
print 'Not a Number, Try Again.'
continue
i -= 1
PosList[i] = Turn
self.UpdateBoard
self.WinChecker
if Winx == True:
print 'X Wins!'
sys.exit()
elif Wino == True:
print 'O Wins!'
sys.exit()
self.UpdateTurn
s = Main()
s.Starter
我刚刚(4天)完成了python自己的教程。您还没有调用该方法
s.Starter()
实际上,您并没有在最后一行中调用
Starter
方法,只是引用了它。改为这样做:
s.Starter()
这就叫它。调用Starter函数,比如
s.Starter()
而且可能存在逻辑错误,下面的while循环始终为真
def Starter(self):
while True:
try:
i = int(input(''))
except TypeError:
print 'Not a Number, Try Again.'
continue
出于兴趣,这里有一个重写版本。我使用了一些更高级的构造-
@classmethod
和@property
以及像\uuuu str\uuu
和\uu repr\uuu
这样的“神奇方法”。希望你觉得它有用
def getInt(prompt='', lo=None, hi=None):
"""
Get integer value from user
If lo is given, value must be >= lo
If hi is given, value must be <= hi
"""
while True:
try:
val = int(raw_input(prompt))
if lo is not None and val < lo:
print("Must be at least {}".format(lo))
elif hi is not None and val > hi:
print("Must be no more than {}".format(hi))
else:
return val
except ValueError:
print("Must be an integer!")
class TicTacToe(object):
players = ('X', 'O') # player characters
blank = ' ' # no-player character
wins = ( # lines that give a win
(0,1,2),
(3,4,5),
(6,7,8),
(0,3,6),
(1,4,7),
(2,5,8),
(0,4,8),
(2,4,6)
)
board_string = '\n'.join([ # format string
"",
"+---+---+---+",
"| {} | {} | {} |",
"+---+---+---+",
"| {} | {} | {} |",
"+---+---+---+",
"| {} | {} | {} |",
"+---+---+---+"
])
@classmethod
def ch(cls, state):
"""
Given the state of a board square (None or turn number)
return the output character (blank or corresponding player char)
"""
if state is None:
return cls.blank
else:
return cls.players[state % len(cls.players)]
def __init__(self, bd=None):
"""
Set up a game of TicTacToe
If board is specified, resume playing (assume board state is valid),
otherwise set up a new game
"""
if bd is None:
# default constructor - new game
self.turn = 0
self.board = [None for i in range(9)]
elif hasattr(bd, "board"): # this is 'duck typing'
# copy constructor
self.turn = sum(1 for sq in bd if sq is not None)
self.board = bd.board[:]
else:
# given board state, resume game
self.turn = sum(1 for sq in bd if sq is not None)
self.board = list(bd)
@property
def board_chars(self):
"""
Return the output characters corresponding to the current board state
"""
getch = type(self).ch
return [getch(sq) for sq in self.board]
@property
def winner(self):
"""
If the game has been won, return winner char, else None
"""
bd = self.board_chars
cls = type(self)
for win in cls.wins:
c0, c1, c2 = (bd[sq] for sq in win)
if c0 != cls.blank and c0 == c1 and c0 == c2:
return c0
return None
def __str__(self):
"""
Return a string representation of the board state
"""
cls = type(self)
return cls.board_string.format(*self.board_chars)
def __repr__(self):
"""
Return a string representation of the object
"""
cls = type(self)
return "{}({})".format(cls.__name__, self.board)
def do_move(self):
"""
Get next player's move
"""
cls = type(self)
next_player = cls.ch(self.turn)
while True:
pos = getInt("Player {} next move? ".format(next_player), 1, 9) - 1
if self.board[pos] is None:
self.board[pos] = self.turn
self.turn += 1
break
else:
print("That square is already taken")
def play(self):
print("Welcome to Tic Tac Toe. Board squares are numbered 1-9 left-to-right, top-to-bottom.")
while True:
print(self) # show the board - calls self.__str__
w = self.winner
if w is None:
self.do_move()
else:
print("{} is the winner!".format(w))
break
def main():
TicTacToe().play()
if __name__=="__main__":
main()
def getInt(提示符=“”,低=无,高=无):
"""
从用户获取整数值
如果给定lo,则值必须大于等于lo
若给定hi,则值必须为,Python中的方法用括号调用执行这个方法。这里还有另一个问题。你永远不会跳出输入循环。在他们给出一个有效的答案之前,我永远不会跳出输入循环。好吧,这就是我的想法。好吧,试过了,你是对的,需要解决这个问题…实际上我只是忘记了缩进函数的其余部分。我需要注意下一次。谢谢你的回答,这样我就不用再看代码了。