1

I'm trying to get to grips with classes in python and explore javascript, so decided to convert a maze program in javascript as an learning exercise. However, I'm stuck early on with the concept of declaring classes for the directions of travel. Can someone help me out?

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);

Here is my attempt in python, which fails because I use SOUTH before defining, but don't know the python equivalent of arrow function which returns an element not yet declared:

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)
1
  • Why not just use an Enum? Commented Apr 13, 2020 at 1:05

1 Answer 1

3

You should just turn your class into an enum and reference directions as members of the enum so they do not resolve at definition time (which gets you an error of referencing a variable before assignment) but only when actually used.

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.