Instance initializers

This class isn't very useful, because it can only represent one particular flight. We need to make the flight number configurable at the point a Flight is created. To do that we need to write an initializer method.

If provided, the initializer method is called as part of the process of creating a new object when we call the constructor. The initializer method must be called __init__() delimited by the double underscores used for Python runtime machinery. Like all other instance methods, the first argument to __init__() must be self.

In this case, we also pass a second formal argument to __init__() which is the flight number:

class Flight:

def __init__(self, number):
self._number = number

def number(self):
return self._number

The initializer should not return anything – it simply modifies the object referred to by self.

If you're coming from a Java, C#, or C++ background it's tempting to think of __init__() as being the constructor. This isn't quite accurate; in Python the the purpose of __init__() is to configure an object that already exists by the time __init__() is called. The self argument is, however, analogous to this in Java, C#, or C++. In Python the actual constructor is provided by the Python runtime system and one of the things it does is check for the existence of an instance initializer and call it when present.

Within the initializer we assign to an attribute of the newly created instance called _number . Assigning to an object attribute that doesn't yet exist is sufficient to bring it into existence.

Just as we don't need to declare variables until we create them, neither do we need to declare object attributes before we create them. We choose _number with a leading underscore for two reasons. First, because it avoids a name clash with the method of the same name. Methods are functions, functions are objects, and these functions are bound to attributes of the object, so we already have an attribute called number and we don't want to replace it. Second, there is a widely followed convention that the implementation details of objects which are not intended for consumption or manipulation by clients of the object should be prefixed with an underscore.

We also modify our number() method to access the _number attribute and return it.

Any actual arguments passed to the flight constructor will be forwarded to the initializer, so to create and configure our Flight object we can now do this:

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

We can also directly access the implementation details:

>>> f._number
SN060

Although this is not recommended for production code, it's very handy for debugging and early testing.

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

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