猿问

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)


慕慕森
浏览 144回答 1
1回答

慕神8447489

你应该把你的类变成一个枚举并引用方向作为枚举的成员,这样它们就不会在定义时解析(这会让你在赋值之前引用一个变量的错误),但只有在实际使用时才解析。from enum import Enumclass 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)
随时随地看视频慕课网APP

相关分类

Python
我要回答