0

I have a class Flight, and I'm trying initialize it, but I have a syntax error in

print x=Flight(flightFromInput='nebrasca')

This is a content of my example file

class Flight:
    flightFrom = None
    flightTo = None
    departureDate = None
    arrivalDate=None
    airline=None
    serviceClass=None
    departureAirport = None
    arrivalAirport=None


    #----------------------------------------------------------------------
    def __init__(self,flightFromInput):
        self.flightFrom = flightFromInput

print x=Flight(flightFromInput='nebrasca')

What is wrong with this code?

19
  • 4
    it's always a good idea to write what error u get. Commented Jan 26, 2011 at 14:44
  • 4
    Also: Do you realize that variables created in class scope (in your code, every assignment above #-----...) are class variables, i.e. shared among instances, and not instance variables (self....)? Commented Jan 26, 2011 at 14:45
  • 1
    @delnan: The class variables can act as fall-backs. If you assign to .flightFrom on an instance, you won't change the class variable, so semantically this is ok. (You might have objections regarding the style, though.) Commented Jan 26, 2011 at 14:47
  • 1
    @Sven: That why I asked "do you realize" instead of writng "your code is propably broken". But yes, I do wonder if this is the best solution. Commented Jan 26, 2011 at 14:50
  • 1
    @S.Lott: It's not entirely unreasonable to expect assignment to be an expression (there are many popular languages that do this). Especially given that OP seems to know some of those (e.g. asked C# questions). Commented Jan 26, 2011 at 14:55

3 Answers 3

8

You should write

x = Flight(flightFromInput='nebrasca')
print x
Sign up to request clarification or add additional context in comments.

Comments

4

In python an assignment statement doesn't return the assigned value. So you cannot use it within another statement. As the other answers suggested, you can work around this by printing x in a separate line.

Note, that there are exceptions though:

a = b = 0 # works
a = (b = 0) # does not work

The first case is a special case allowed for convenience when you want to assign the same value to multiple variables. In the second case you clearly tell the compiler that b=0 is a separate statement, but as it doesn't return a value the outer assignment to a leads to the resulting SyntaxError.

Hope this explains it a bit more clearly, why you should do print x after assigning it.

Comments

1

Contrary to C, in Python assignments are statements only and not expressions. Therefore they do not have their own value. Try this:

x = Flight(flightFromInput='nebrasca')
print x

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.