javascript - 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)
解决方案
你应该把你的类变成一个枚举并引用方向作为枚举的成员,这样它们就不会在定义时解析(这会让你在赋值之前引用一个变量的错误),但只有在实际使用时才解析。
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)
推荐阅读
- python - 无法在 Windows 上运行 Pangolin pyexamples
- spring-boot - Kotlin copy() 函数正在 JPA 实体上创建一个新 Id,从而产生一个新行
- javascript - Javascript使用选项将单列html更改为多列
- .htaccess - 子域的不完整 htaccess
- kubernetes - 在 Kubernetes 1.10 中禁用 heapster 健康检查
- eclipse - Maven 和 Eclipse 使用的 Checkstyle 配置
- c++ - 我的二进制搜索程序简单地关闭了
- c# - 不使用 await 的危险
- angular - 发送表单数据以及 angular6 中上传的文件显示错误 title1 和 title2 not found
- python - 如何在python中制作多边形雷达(蜘蛛)图