调用时函数未定义错误

时间:2018-03-18 01:55:36

标签: python python-3.x python-2.7 list

所以即时返回两个输入并希望在另一个函数中使用它们,当我运行代码时,它表示返回代码的函数未定义。知道问题可能是什么?

棋盘类:

class ChessBoard(tk.Frame):
       def __init__(self, parent, rows=8, columns=8, size=70, color1="white", color2="lightgrey"):

       self.rows = rows
       self.columns = columns
       self.size = size
       self.color1 = color1
       self.color2 = color2
       self.pieces = {}

返回两个输入的函数:

    def UserInput(self): #Tester Function

      count = 0

      while count < 2:

          KingRow = int(input("Choose Row: ")) #mighht not be needed
          KingColumn = int(input("Choose Column: ")) #choose the column

      return KingRow, KingColumn

      count = count + 1

我想在其中使用的功能:

def KingMoves(self, rows, columns):

    FinalMove = []

    c = ChessBoard(parent)

    KingRow, KingColumn = c.UserInput()

    FinalMove.append(((KingRow - 1),(KingColumn))) 
    FinalMove.append(((KingRow + 1),(KingColumn))) 
    FinalMove.append(((KingRow),(KingColumn + 1))) 
    FinalMove.append(((KingRow + 1),(KingColumn + 1))) 
    FinalMove.append(((KingRow - 1),(KingColumn + 1))) 
    FinalMove.append(((KingRow + 1),(KingColumn - 1))) 
    FinalMove.append(((KingRow - 1),(KingColumn - 1))) 

    return FinalMove;

当前错误:

    name 'UserInput' is not defined

2 个答案:

答案 0 :(得分:1)

首先尝试:how to use a Python function with keyword “self” in arguments

如果不起作用请尝试:

Python类中的函数称为方法。它们通常在其他参数之前采用self参数。此外,方法不能直接“看到”彼此;您需要将其称为self.method(args),而不仅仅是method(args)

Source

请参阅,这是我如何调用类中的另一个函数:

def func1(self):
    return "Whoop"

def func2(self):
    whoop = self.func1()
    return whoop

另外,请尝试使用for语句而不是while。你也没有,但它的代码行更少,也更容易。

def UserInput(self): #Tester Function
    for x in range(0, 2):
        KingRow = int(input("Choose Row: ")) #mighht not be needed
        KingColumn = int(input("Choose Column: ")) #choose the column

  return KingRow, KingColumn

答案 1 :(得分:1)

除非你调用ChessBoard类,否则Python不知道UserInput函数的位置/内容。首先调用该类,然后调用其函数:

c = ChessBoard()
KingRow, KingColumn = c.UserInput()
相关问题