Give every book the same starting shape.
The previous lesson introduced a class as a shared model. Now Book can create ready-to-use book objects. __init__ runs when Python creates an object, and self means the particular object being prepared.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
book_one = Book("Dune", "Frank Herbert")
print(book_one.title)Book(...) calls __init__. The values become attributes on this one object: self.title and self.author. The dot reads an attribute from a particular instance.
DuneEvery call to Book(...) creates a new object. The same class definition is shared, but each instance keeps separate attribute values.
Read self as “this book”: Inside __init__, self refers to the object Python is currently creating. You write self.title so each Book receives its own title.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
book_one = Book("Dune", "Frank Herbert")
book_two = Book("The Hobbit", "J. R. R. Tolkien")
book_one.title = "Dune Messiah"
print(book_one.title)
print(book_two.title)Changing book_one.title changes only book_one. book_two still stores The Hobbit.
Book # the class blueprint
book_one = Book(...) # one object, or instanceUse the class name to create objects. Use an object variable and a dot to access its attributes.
Create one library book
- 1. Define the classclass Book names the shared blueprint.
- 2. Initialize data__init__ receives title and author while the object is created.
- 3. Store attributesself.title and self.author belong to that one object.
- 4. Create another instanceAnother Book call creates separate data for another library book.
Common mistakes
- Missing selfInstance methods need self first so Python knows which object receives the data.
- Using title instead of self.titleA parameter is temporary; self.title saves the value as an object attribute.
- Expecting shared instance dataChanging one Book instance does not update another instance.
- Forgetting parenthesesBook(...) creates an object; Book by itself names the class.
