Classes and instances
A class defines a new type of value. Use one when several pieces of state belong together and a small set of operations should control how they change. A plain function is often enough for a calculation that only needs its arguments.
On this page
Define a class
A reading list has a name and a collection of titles. Each instance should own its own collection.
class ReadingList:
def __init__(self, name):
self.name = name
self.titles = []
def add(self, title):
self.titles.append(title)
shelf = ReadingList("Work")
shelf.add("Python Basics")
print(shelf.name, shelf.titles)Calling ReadingList("Work") creates an instance and initializes its attributes. Python supplies that instance as self when you call a method. The output is Work ['Python Basics'].
Keep instance state independent
The assignment self.titles = [] runs each time an instance is initialized. If you put a single mutable list on the class instead, every instance can end up changing that same list. Create a second reading list and inspect both lists after adding a title to just one.