0

I'm trying to use global variables LAND which is an object of class Type within the class Type.

The following code gives me an error: SyntaxError: invalid syntax because LAND is not defined:

# Define a class named Type
class Type():
    def __init__(self, id, symbol):
        self.id = id
        self.symbol = symbol
    def is_free(self):
        return self.id = LAND.id

# Define variables of this class
LAND = Type(-1, '.')

I can't just move LAND before the definition of Type, because that will also give me the error SyntaxError: invalid syntax because Type is not defined.

Can somebody tell me if it is possible? Or is there any alternative way to do this?


I have asked a question with a bad title Python class forward declaration, it was marked as duplicate with two questions, but as I explained in my original post, I don't think my question is the same as those two:

I have seen the post Is it possible to forward-declare a function in Python?, but I don't think it's the same issue. Because the question is about forward declaration of function, while I'm asking about class.

I also read this post Does Python have class prototypes (or forward declarations)?, but it was asking about refer to a class in another class, while I'm asking about refer to variables of its own type within the class. I don't see my solution in this post, or can somebody who thinks it's duplicate explain a little bit?

timgeb
  • 76,762
  • 20
  • 123
  • 145
zhm
  • 3,513
  • 3
  • 34
  • 55

1 Answers1

3

Following code gives me error, SyntaxError: invalid syntax because LAND is not defined

No, you get a SyntaxError because an assignment a = b (in your specific case
self.id = LAND.id) is not an expression, wich means that it does not produce a value which you would be able to return.

Your code works just fine when you change the = to a ==, which is what I assume you want. Alternatively (I'm a bit unsure what is supposed to happen in your code), you could write two lines:

self.id = LAND.id
return self.id

Anyway, the problem here is not that LAND is not defined when is_free is created. That's not a problem, because nobody is calling is_free yet. The problem is that you probably thought (because you seem to come from a C background ) that an assignment with = produces a value, which is not the case in Python.

timgeb
  • 76,762
  • 20
  • 123
  • 145