首页 > 解决方案 > Python等价于Javascript类和箭头函数

问题描述

我正在尝试掌握 python 中的类并探索 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)

标签: javascriptpython

解决方案


你应该把你的类变成一个枚举并引用方向作为枚举的成员,这样它们就不会在定义时解析(这会让你在赋值之前引用一个变量的错误),但只有在实际使用时才解析。

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)

推荐阅读