我正在嘗試掌握 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,但不知道返回尚未聲明的元素的箭頭函數(shù)的 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條經(jīng)驗 獲得超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)
添加回答
舉報
0/150
提交
取消