gpt4 book ai didi

javascript - Python 相当于 Javascript 类和箭头函数

转载 作者:行者123 更新时间:2023-12-02 21:07:58 25 4
gpt4 key购买 nike

我正在尝试掌握 python 中的类(class)并探索 javascript,因此决定将 javascript 中的迷宫程序转换为学习练习。然而,我很早就陷入了为行进方向声明类的概念。有人可以帮我吗?

class Direction {
constructor(char, reverse, increment,mask) {
this.char = char;
this.reverse = reverse;
this.increment = increment;
this.mask = mask;
}
toString() {
return this.char;
}
}

const NORTH = new Direction("⇧", () => SOUTH, (x, y) => [x, y + 1],1);
const SOUTH = new Direction("⇩", () => NORTH, (x, y) => [x, y - 1],2);
const EAST = new Direction("⇨", () => WEST, (x, y) => [x + 1, y],4);
const WEST = new Direction("⇦", () => EAST, (x, y) => [x - 1, y],8);

这是我在 python 中的尝试,它失败了,因为我在定义之前使用了 SOUTH,但不知道箭头函数的 python 等效项,该函数返回尚未声明的元素:

class Direction:

def __init__(self, char,reverse,increment,mask):
self.char = char
self.reverse = reverse
self.increment = increment
self.mask = mask

def __str__(self):
return self.char

NORTH = Direction("⇧", SOUTH, [x, y + 1],1)
SOUTH = Direction("⇩", NORTH, [x, y - 1],2)
EAST = Direction("⇨", WEST, [x + 1, y],4)
WEST = Direction("⇦", EAST, [x - 1, y],8)

最佳答案

您应该将您的类转换为枚举并作为枚举成员引用方向,这样它们就不会在定义时解析(这会导致您在赋值之前引用变量的错误),而仅在实际使用时解析。

from enum import Enum

class Direction(Enum):
def __init__(self, char, reverse, increment, mask):
self.char = char
self.reverse = reverse
self.increment = increment
self.mask = mask

def __str__(self):
return self.char


NORTH = Direction("⇧", Direction.SOUTH, [x, y + 1], 1)
SOUTH = Direction("⇩", Direction.NORTH, [x, y - 1], 2)
EAST = Direction("⇨", Direction.WEST, [x + 1, y], 4)
WEST = Direction("⇦", Direction.EAST, [x - 1, y], 8)

关于javascript - Python 相当于 Javascript 类和箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61175965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com