A library has many related things.
Procedural code can keep a title and author in separate variables or dictionaries. As a library grows, object-oriented programming (OOP) gives each book a shared model, its own data, and later its own behavior.
title_one = "Dune"
author_one = "Frank Herbert"
title_two = "The Hobbit"
author_two = "J. R. R. Tolkien"These variables work, but the connection between each title and author is something the programmer must keep organized.
A class is a blueprint for similar objects. An object is one concrete instance. In the next lesson, you will define the Book class in detail; for now, notice that each book object can hold its own attributes.
Mini Library Manager: This module will gradually turn the book model into a small library application.
class Book:
pass
book_one = Book()
book_two = Book()
book_one.title = "Dune"
book_two.title = "The Hobbit"
book_one.title = "Dune Messiah"
print(book_one.title)
print(book_two.title)book_one and book_two come from the same Book class, but changing book_one.title does not change book_two.title.
book.title = "Dune"
book.author = "Frank Herbert"
# Later, a book can also have behavior, such as borrowing.Attributes describe an object’s data. Methods will describe behavior in a later lesson.
Follow the model
- 1. Find related dataA book has related information such as a title and an author.
- 2. Choose a shared modelA class describes what similar book objects have in common.
- 3. Create instancesEach object represents one concrete book in the library.
- 4. Keep state separateChanging one object’s attributes does not change another object’s attributes.
Common mistakes
- Treating a class as one bookA class is the shared definition; an object is a particular book.
- Expecting objects to share every valueInstance attributes belong to the object where they are assigned.
- Rushing into constructorsFirst understand the model and instance; constructors come in the next lesson.
- Forgetting the dotUse object.attribute to read or assign data for one object.
