Instance methods

Let's make our class a little more interesting, by adding a so-called instance method which returns the flight number. Methods are just functions defined within the class block, and instance methods are functions which can be called on objects which are instances of our class, such as f. Instance methods must accept a reference to the instance on which the method was called as the first formal argument, and by convention this argument is always called self.

We have no way of configuring the flight number value yet, so we'll just return a constant string:

class Flight:

def number(self):
return "SN060"

And from a fresh REPL:

>>> from airtravel import Flight
>>> f = Flight()
>>> f.number()
SN060

Notice that when we call the method, we do not provide the instance f for the actual argument self in the argument list. That's because the standard method invocation form with the dot, like this:

>>> f.number()
SN060

Is simply syntactic sugar for:

>>> Flight.number(f)
SN060

If you try the latter, you'll find that it works as expected, although you'll almost never see this form used for real.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset