【问题标题】:How to use variables from one function in another in python? Where the only difference in functions is the return statement如何在python中使用另一个函数中的变量?函数的唯一区别是 return 语句
【发布时间】:2019-09-30 03:48:52
【问题描述】:

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

heuristic 和 heuristic2 是原始函数,理想情况下,我会将两者之一转换为 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)

【问题讨论】:

  • 似乎两个函数都是相同的,如果只是返回不同,然后编写一个具有不同条件的函数。
  • 这段代码能运行吗? distanceToSquare 在使用之前从未分配过

标签: python function return


【解决方案1】:

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

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

【讨论】:

    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 2011-11-28
      • 2012-09-28
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多