![](/img/trans.png)
[英]Python: How to use named variables from one function in other functions
[英]How to use variables from one function in another in python? Where the only difference in functions is the return statement
除了返回语句之外,我有两个完全相同的函数。 如何使用一个 function 中的变量来缩短第二个 function?
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)
看看所谓的“全局”变量: https://www.programiz.com/python-programming/global-local-nonlocal-variables
从本质上讲,在 function 外部定义的变量将允许所有函数能够访问和操作该变量,而在 function 内部定义的变量是“本地”的,只能在该特定 ZC1C425268E68384F1AB47A 中使用。
不,您不能直接访问 function 中变量的 state。 如果您想访问这样的变量
heuristic2(state).distanceToSquare
然后你必须让heuristic2
返回一个 class 属性为distanceToSquare
class Heuristic():
def __init__(self, val, dis, dirt):
self.value = value
self.distanceToSquare = dis
self.numDirtySquares = dirt
并调整 return 语句以将每个值作为 class 的一部分返回
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.