Give a new book its starting state.
You already used __init__ to receive a title and author. A constructor can also set a default value. Here, every new book is available unless the caller says otherwise.
class Book:
def __init__(self, title, author, available=True):
self.title = title
self.author = author
self.available = available
dune = Book("Dune", "Frank Herbert")
print(dune.available)title and author are required arguments, so every Book call must provide them. available=True is a default argument, so it is used when no third value is supplied.
TrueAfter creation, an attribute can change. Assigning dune.available = False updates only the dune object.
Constructor checklist: Use self first, receive the values you need, and save them with self.attribute. Defaults belong in the parameter list after required arguments.
class Book:
def __init__(self, title, author, available=True):
self.title = title
self.author = author
self.available = available
dune = Book("Dune", "Frank Herbert")
foundation = Book("Foundation", "Isaac Asimov", False)
dune.available = False
print(dune.available)
print(foundation.available)dune starts with the default True and is then changed to False. foundation receives False directly when it is created.
Book("Dune", "Frank Herbert")
# title and author are required
Book("Foundation", "Isaac Asimov", False)
# available overrides its defaultRequired arguments describe information every book must have. A default makes optional state convenient while keeping a predictable starting value.
Build a reliable constructor
- 1. Receive required dataPut title and author in __init__ so a Book cannot be created without them.
- 2. Add optional statePlace available=True after required parameters to give new books a default availability.
- 3. Save on selfAssign self.available = available so the value belongs to this instance.
- 4. Update one bookUse book.available = False when that particular book is borrowed.
Common mistakes
- Putting a default before required dataRequired parameters must come before default parameters in a function definition.
- Forgetting to save a parameterReceiving available is not enough; assign it to self.available to store it on the object.
- Changing the class instead of the objectWrite dune.available = False to change one book’s state.
- Expecting a default to overwrite a supplied valueA default is used only when the caller leaves that argument out.
