user278618
user278618

Reputation: 20232

I cannot initialize class in python

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?

Upvotes: 0

Views: 1616

Answers (3)

Frank
Frank

Reputation: 10571

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.

Upvotes: 4

thkala
thkala

Reputation: 86333

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

Upvotes: 1

Don
Don

Reputation: 17606

You should write

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

Upvotes: 8

Related Questions