One library, many individual books.
Put a class attribute directly inside Book to share it. Put an instance attribute on self in __init__ to give each book its own value.
class Book:
library_name = "Mini Library"
def __init__(self, title, author):
self.title = title
self.author = author
self.is_available = True
book = Book("Dune", "Frank Herbert")
print(Book.library_name)
print(book.title)library_name belongs to the Book class and is shared. title belongs to book, because self.title creates an attribute on that one instance.
Mini Library
DuneChanging Book.library_name updates the shared lookup for instances that do not have their own library_name. Assigning book.library_name creates a separate instance attribute that shadows the class attribute.
Attribute lookup order: When Python reads book.library_name, it checks the book first and then the Book class. An instance value therefore hides the shared value for that one book.
class Book:
library_name = "Mini Library"
def __init__(self, title, author):
self.title = title
self.author = author
self.is_available = True
book_one = Book("Dune", "Frank Herbert")
book_two = Book("The Hobbit", "J. R. R. Tolkien")
Book.library_name = "City Library"
book_one.library_name = "Personal Shelf"
print(book_one.library_name)
print(book_two.library_name)Book.library_name changes the shared name to City Library. book_one then gets its own Personal Shelf value, while book_two still uses the class value.
class Book:
library_name = "Mini Library" # class attribute
def __init__(self, title):
self.title = title # instance attributeUse a class attribute for one value shared by all books. Use an instance attribute for data that can differ from book to book.
Trace an attribute lookup
- 1. Read the instance firstbook_one.library_name first looks for library_name on book_one.
- 2. Fall back to the classWithout an instance value, Python reads Book.library_name.
- 3. Change shared stateBook.library_name = "City Library" changes the value used by unshadowed instances.
- 4. Shadow one instancebook_one.library_name = "Personal Shelf" affects only book_one.
Common mistakes
- Using a shared list for per-book dataA mutable class attribute such as tags = [] is shared by every instance. Create a new list on self in __init__ when each book needs its own tags.
- Expecting an instance assignment to update all booksbook_one.library_name creates or changes book_one’s value only; it does not change Book.library_name.
- Calling every attribute sharedtitle, author, and is_available are instance attributes because they are assigned through self.
- Forgetting the class name for a shared updateUse Book.library_name to deliberately update the value shared by the class.
