Python:名称未定义错误,即使函数在调用前已明确定义

标签 python python-3.x function compiler-errors

我是 python 新手,对函数定义有一个奇怪的问题。我已经检查了论坛并确保在调用它之前定义我的函数,但这并没有帮助解决问题。当我尝试在这个特定方法中调用字面函数时,我不断收到名称未定义错误。

from eight_puzzle import Puzzle
import math


################################################################
### Node class and helper functions provided for your convience.
### DO NOT EDIT!
################################################################
class Node:
    """
    A class representing a node.
    - 'state' holds the state of the node.
    - 'parent' points to the node's parent.
    - 'action' is the action taken by the parent to produce this node.
    - 'path_cost' is the cost of the path from the root to this node.
    """
    def __init__(self, state, parent, action, path_cost):
        self.state = state
        self.parent = parent
        self.action = action
        self.path_cost = path_cost

    def gen_child(self, problem, action):
        """
        Returns the child node resulting from applying 'action' to this node.
        """
        return Node(state=problem.transitions(self.state, action),
                    parent=self,
                    action=action,
                    path_cost=self.path_cost + problem.step_cost(self.state, action))

    @property
    def state_hashed(self):
        """
        Produces a hashed representation of the node's state for easy
        lookup in a python 'set'.
        """
        return hash(str(self.state))

################################################################
### Node class and helper functions provided for your convience.
### DO NOT EDIT!
################################################################
def retrieve_solution(node,num_explored,num_generated):
    """
    Returns the list of actions and the list of states on the
    path to the given goal_state node. Also returns the number
    of nodes explored and generated.
    """
    actions = []
    states = []
    while node.parent is not None:
        actions += [node.action]
        states += [node.state]
        node = node.parent
    states += [node.state]
    return actions[::-1], states[::-1], num_explored, num_generated

################################################################
### Node class and helper functions provided for your convience.
### DO NOT EDIT!
################################################################
def print_solution(solution):
    """
    Prints out the path from the initial state to the goal given
    a tuple of (actions,states) corresponding to the solution.
    """
    actions, states, num_explored, num_generated = solution
    print('Start')
    for step in range(len(actions)):
        print(puzzle.board_str(states[step]))
        print()
        print(actions[step])
        print()
    print('Goal')
    print(puzzle.board_str(states[-1]))
    print()
    print('Number of steps: {:d}'.format(len(actions)))
    print('Nodes explored: {:d}'.format(num_explored))
    print('Nodes generated: {:d}'.format(num_generated))


################################################################
### Skeleton code for your Astar implementation. Fill in here.
################################################################
class Astar:
    """
    A* search.
    - 'problem' is a Puzzle instance.
    """
    def __init__(self, problem):
        self.problem = problem
        self.init_state = problem.init_state
        self.num_explored = 0
        self.num_generated = 1




    def selectState(self, listOfStates):
        '''
        Selects the loweset cost node for expansion based on f(n) = g(n) + h(n)
        '''
        lowestCostPath = listOfStates[0].path_cost
        index = int(1)
        lowestNodeIndex = int(0)
        while index != len(listOfStates):
            scannedPathCost = listOfStates[index].path_cost
            if index  < scannedPathCost:
                lowestCostPath = scannedPathCost
                lowestNodeIndex = index
            index += 1
        return listOfStates[lowestNodeIndex]


    def f(self,node, method):
        '''
        Returns a lower bound estimate on the cost from root through node
        to the goal.
        '''
        return node.path_cost + self.h(node, method)



    def getManhattanDistance(self, node):
        '''
        Evaluates the manhattan distance for a given state 
        '''
        iterator = int(0)
        misplacedCount = int(0)
        totalDistance = int(0)
        while iterator != len(node.state):
            if iterator != node.state[iterator] and node.state[iterator] != 0:
                misplacedCount = misplacedCount + 1
                xCurrent = int(node.state[iterator]/3)
                yCurrent = int(node.state[iterator]%3)
                xDesired = int(iterator/3)
                yDesired = int(iterator%3)
                totalDistance = totalDistance + int(abs(xCurrent - xDesired)) + int(abs(yCurrent - yDesired))
            iterator = iterator + 1
        return totalDistance + misplacedCount

    def h(self,node, method='man'):
        '''
        Returns a lower bound estimate on the cost from node to the goal
        using the different heuristics. 
        '''
        ################################################################
        ### Your code here.
        ################################################################
        if method == 'man':
            self.getManhattanDistance(node)
            return -1
        elif method == 'rowcol':
            return -1 # compute rowcol heuristic
        elif method == 'misplaced':
            return -1 # compute misplaced tiles the number of tiles out of place
        elif method == 'null':
            return -1 # compute null heuristic
        else:
            return 0

    def method_stats(self, board, trials=100, method='man'):
        '''
        Returns an mean and standard deviation of the number of nodes expanded
        '''
        # write code here to randomly generate puzzles and
        # compute the mean and standard deviation of the number
        # nodes expanded. You can use np.mean() and np.std()

        expanded_mean = 0.
        expanded_std = 0.
        for t in range(trials):
            puzzle = Puzzle(board).shuffle()
            solver = Astar(puzzle)
            actions, states, num_explored, num_generated = solver.solve(method=method)
            ############################################################
            ### Compute upper bound for branching factor and update b_hi
            ### Your code here.
            ############################################################
        return expanded_mean, expanded_std

    def anotherFunction(self, node, method):
        return 1

    def generateStatesFor(self, node, method, listOfStates):
        '''
        Decides how to select an action from a list of available actions
        '''
    def solve(self, method='man'):
        node = Node(state = self.init_state,
            parent = None,
            action = None,
            path_cost = 0)
        num_explored = int(0)
        num_generated = int(0)
        listOfStates = []
        listOfStates.append(node)
        print(listOfStates[0].state)
        anotherFunction(self, node, method)
        return retrieve_solution(node, num_explored=num_explored, num_generated=num_generated)

if __name__ == '__main__':
    # Simple puzzle test
   ## board = [[3,1,2],
    ##         [4,0,5],
    ##         [6,7,8]]
    board = [[7,2,4],
             [5,0,6],
             [8,3,1]]

    puzzle = Puzzle(board)
    solver = Astar(puzzle)
    solution = solver.solve()
    ##print_solution(solution)

    # Harder puzzle test
    board = [[7,2,4],
             [5,0,6],
             [8,3,1]]

    puzzle = Puzzle(board)
    solver = Astar(puzzle)
    ##solution = solver.solve()
    ##print(len(solution[0]))

    # branching factor test
    method='man'
    emean, estd = solver.method_stats(board, trials=100, method=method)
    ##print('mean and standard deviation: {0:.2f}, {1:.2f} using heuristic: {2}'.format(emean, estd, method))

错误代码:

    Traceback (most recent call last): File "/Users/-/Downloads/HW1 2/code/my_hw1.py", line 214, in <module>
solution = solver.solve() File "/Users/-/Downloads/HW1 2/code/my_hw1.py", line 200, in solve
anotherFunction(self, node, method) NameError: name 'anotherFunction' is not defined [Finished in 0.1s with exit code 1]

正如您所看到的,调用它的函数位于第 200 行,并且该函数在第 185 行定义。知道问题可能是什么吗?我还可以从其他无法解决的方法中调用完全相同的“anotherFunction”方法。任何提示将不胜感激。

最佳答案

当您定义一个以“self”作为参数的函数时,您需要从定义该函数的类中调用该函数。例如,如果您有一个 myClass 类的实例,其中定义了 anotherFunction,则语法将为 myClass.anotherFunction(node, method)。定义中的“self”参数表明 anotherFunction 是它定义的任何类的成员函数 - 我需要查看更多代码才能知道那是什么类。

关于Python:名称未定义错误,即使函数在调用前已明确定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48750835/

相关文章:

python - 成功单元测试pyinotify?

python - Kivy 在 Samsung Exynos5422 w/Mali-T628 MP6 上表现不佳

python - Pandas - 多列上的 idxmin 保持所有关系

python - 如何使已打开的文件可读(例如 sys.stdout)?

python - 转置列表子集维度?

python - 从 pandas 数据帧中提取子集确保不重叠?

python - 创建随机值并将其传递给具有硬边界的 Pandas 数据帧

javascript - 创建一个函数,该函数接受具有姓名和年龄属性的人员对象

function - golang中固定cos数学函数有没有解决办法

matlab - 一个函数如何在 Julia 中有多个返回值(相对于 MATLAB)?