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

标签 javascript python

我正在尝试掌握 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/

相关文章:

javascript - 如何阻止来自 Facebook 引荐来源网址的 _isMatchingDomain 引用错误?

python - 添加到现有电子表格?

python - 是什么使得可选参数是可选的而位置参数是必需的?

javascript - 将 css 样式添加到 Javascript 中使用的图像

javascript - 无法找出 react 虚拟化列表的重复行/项目问题

javascript - 当稍后再次设置派生对象的属性时,从基对象继承的属性会发生什么情况?

python - 使用 Python 跟踪 Linux 命令

python - 'for x in list:' 和 'for x in list[:]:' 有什么区别

python - 使用 CA 发布的数字证书签署 PDF 文档的 Web 应用程序

javascript - 在页面刷新时更改背景图像