Book Image

The Python Apprentice

By : Robert Smallshire, Austin Bingham
Book Image

The Python Apprentice

By: Robert Smallshire, Austin Bingham

Overview of this book

Experienced programmers want to know how to enhance their craft and we want to help them start as apprentices with Python. We know that before mastering Python you need to learn the culture and the tools to become a productive member of any Python project. Our goal with this book is to give you a practical and thorough introduction to Python programming, providing you with the insight and technical craftsmanship you need to be a productive member of any Python project. Python is a big language, and it’s not our intention with this book to cover everything there is to know. We just want to make sure that you, as the developer, know the tools, basic idioms and of course the ins and outs of the language, the standard library and other modules to be able to jump into most projects.
Table of Contents (21 chapters)
Title Page
Credits
About the Authors
www.PacktPub.com
Customer Feedback
Preface
12
Afterword – Just the Beginning

Sometimes the only object you need is a function


Now we'll show how it's quite possible to write nice object-oriented code without needing classes. We have a requirement to produce boarding cards for our passengers in alphabetical order. However, we realize that the Flight class is probably not a good home for details of printing boarding passes. We could go ahead and create a BoardingCardPrinter class, although that is probably overkill. Remember that functions are objects too and are perfectly sufficient for many cases. Don't feel compelled to make classes without good reason.

Rather than have a card printer query all the passenger details from the flight, we'll follow the object-oriented design principle of "Tell! Don't Ask." and have the Flight tell a simple card printing function what to do.

First the card printer, which is just a module level function:

def console_card_printer(passenger, seat, flight_number, aircraft):
    output = "| Name: {0}"     \
             "  Flight: {1}"   \...