如何在python中使用函数中的变量?函数的唯一区别是返回语句

2024-07-08 14:42:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个完全相同的函数,除了return语句。 如何使用一个函数中的变量来缩短第二个函数

heuristicheuristic2是原始函数,理想情况下,我会将其中一个转换成heuristic3之类的函数

这些不是完整的函数,但是仅仅足够让我了解我要做的事情

def heuristic(self, state):
    for currentState in argsWith0:
        endX = (currentState - 1) // 3
        endY = (currentState - 1) % 3
        newSquare = state[currentState]
        currentDistanceToDirtyNode = abs(endX - startX) + abs(endY - startY)
        if currentDistanceToDirtyNode < distanceToSquare:
            distanceToSquare = currentDistanceToDirtyNode
    return 2 * (distanceToSquare * numDirtySquares + 1) + sum( \
        (numDirtySquares - x) * 4 + 1 for x in range(0, numDirtySquares + 1))


def heuristic2(self, state):
    for currentState in argsWith0:
        endX = (currentState - 1) // 3
        endY = (currentState - 1) % 3
        newSquare = state[currentState]
        currentDistanceToDirtyNode = abs(endX - startX) + abs(endY - startY)
        if currentDistanceToDirtyNode < distanceToSquare:
            distanceToSquare = currentDistanceToDirtyNode
    return 2 * (distanceToSquare * numDirtySquares + 1) + sum( \
        (numDirtySquares - x) * 4 + 1 for x in range(0, numDirtySquares + 1))


def heuristic3(self, state):
    return heuristic2(state) + 2 * \
           (heuristic2(state).distanceToSquare * heuristic2(state).numDirtySquares + 1)

Tags: 函数inselfforreturndefabsstate
2条回答

不,不能直接访问函数中变量的状态。如果您想访问这样的变量

heuristic2(state).distanceToSquare

然后必须使heuristic2返回一个具有distanceToSquare属性的类

class Heuristic():
    def __init__(self, val, dis, dirt):
        self.value = value
        self.distanceToSquare = dis
        self.numDirtySquares = dirt

并调整return语句以将每个值作为类的一部分返回

v = 2 * (distanceToSquare * numDirtySquares + 1) + sum( \
        (numDirtySquares - x) * 4 + 1 for x in range(0, numDirtySquares + 1))
return Heuristic(v, distanceToSquare, numDirtySquares)

def heuristic3(self, state):
    h2 = heuristic2(state)
    return h2.value + 2 * (h2.distanceToSquare * h2.numDirtySquares + 1)

看看所谓的“全局”变量:https://www.programiz.com/python-programming/global-local-nonlocal-variables

从本质上讲,在函数外部定义的变量将允许所有函数都能够访问和操作该变量,而在函数内部定义的变量是“局部”的,只能在该特定函数中使用

相关问题 更多 >

    热门问题