Put book behavior beside book data.
Attributes describe a book’s state. Methods describe what that particular book can do. Each method receives self first, so it can read or update the attributes of the instance that called it.
class Book:
def __init__(self, title, author, available=True):
self.title = title
self.author = author
self.available = available
def borrow(self):
self.available = False
dune = Book("Dune", "Frank Herbert")
dune.borrow()
print(dune.available)Calling dune.borrow() makes Python pass dune as self. The method changes dune.available, not the availability of every book.
FalseA second instance calls the same method definition with a different self. That is why one book can be borrowed while another stays available.
Read self as “this book”: Inside borrow, self.available means the available attribute of the Book instance before the dot in dune.borrow().
class Book:
def __init__(self, title, author, available=True):
self.title = title
self.author = author
self.available = available
def borrow(self):
self.available = False
def return_book(self):
self.available = True
def display_info(self):
print(f"{self.title} by {self.author}: {self.available}")
dune = Book("Dune", "Frank Herbert")
hobbit = Book("The Hobbit", "J. R. R. Tolkien")
dune.borrow()
dune.display_info()
hobbit.display_info()dune.borrow() changes only dune. hobbit has its own available attribute, which remains True.
def borrow(self):
self.available = False
def return_book(self):
self.available = True
def display_info(self):
print(self.title)borrow and return_book change state. display_info reads attributes and shows information without changing the book.
Trace a method call
- 1. Define behavior in the classIndent def borrow(self) inside Book so every Book instance can use it.
- 2. Call it with a dotdune.borrow() selects the borrow behavior for the dune instance.
- 3. Python supplies selfPython passes dune as self, so self.available refers to dune.available.
- 4. Check another instancehobbit.available is independent because hobbit is a different object.
Common mistakes
- Leaving out selfAn instance method needs self first to receive the object that called it.
- Writing available instead of self.availableUse self.available to change the attribute stored on the instance.
- Calling Book.borrow() without an objectUse dune.borrow() so Python knows which Book should be borrowed.
- Expecting one method call to change every instanceA method changes only the object passed as self unless it explicitly works with other objects.
