我正试图摆脱我的全局变量,但我没有成功。
在这种情况下,我让用户在运行程序时指定坐标。从这些坐标开始,我们开始航行(在矩阵内),这意味着我拥有的控制运动的功能需要从输入功能访问这些坐标。移动功能也需要为坐标分配新值。
koordx = 0
koordy = 0
distancetraveled = 0
def input ():
global koordx
global koordy
koordx = int(input ("Assign Y coordinate)"))
koordy = int(input("Assign Y coordinate"))
..... etc
这是移动的例子,改变了坐标。
def north ():
global distancetraveled
distancetraveled += 2
global koordy
koordy -= 1
def northeast():
global distancetraveled
distancetraveled += 2
global koordx
koordx += 1
global koordy
koordy -= 1
def movement():
if... . .. :
northeast() etc... #moves northeast
input()
movement()
这只是一个示例,我还有一些函数需要访问这些坐标及其值。我怎样才能顺利地摆脱我的全局变量?
这只是我修改的代码的一部分,以便更容易理解我需要帮助的内容。
如有任何提示,我们将不胜感激。
最佳答案
您可以创建一个 Boat 类,并将坐标和距离封装在 Boat 实例中:
class Boat:
def __init__(self, x, y, dist=0):
self.x = x
self.y = y
self.dist=dist
然后您可以创建对 Boats 进行操作的函数,并修改这些变量,或者您可以在 Boat 类中创建对变量进行操作的方法(这是一种更面向对象的方式,并封装状态更好)
关于python - 避免使用 Python 中的全局变量,我有几个函数可以更改一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20313086/