为了账号安全,请及时绑定邮箱和手机立即绑定

Python等价于Javascript类和箭头函数

Python等价于Javascript类和箭头函数

慕慕森 2022-10-06 19:35:26
我正在尝试掌握 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.charNORTH = 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)
查看完整描述

1 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

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


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)


查看完整回答
反对 回复 2022-10-06
  • 1 回答
  • 0 关注
  • 143 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号