Classes and objects in Python let you bundle data together with the functions that work on that data. A class is the blueprint, and an object is one thing that was built from that blueprint. Each object holds its own copy of the data while sharing the behaviour that the blueprint describes.
This is the first lesson in the Python Classes and Objects module, and the next lesson in this module is about "__init__ and Instance Attributes Explained".
Concretely, a class statement creates a new type, and calling that type creates an instance. The instance gets its own attributes, which is its own state, and it reaches the methods of the class for its behaviour. That split between state and behaviour is the whole idea, and once it clicks, the rest of Python's object model stops feeling arbitrary.
How do you define your first class?
You write class Name: and then you indent the body. Inside that body, def __init__(self, ...) is the method that Python calls when you build an instance, and it is where you set up the attributes of that instance. Every other method is one that you call on the instance later.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def summary(self):
return f"{self.title} by {self.author} ({self.pages} pages)"
dune = Book('Dune', 'Frank Herbert', 412)
print(dune.title)
print(dune.summary())
print('the class of dune is:', type(dune).__name__)
Read the __init__ signature carefully, because it explains a great deal. The first parameter is self, and Python passes the new instance into it automatically when you write Book(...). Every other parameter is one that you supply yourself. Inside the method, the line self.title = title does not write to a local variable. It attaches a value to that particular object.
Notice that the name has two underscores at each end. That is a convention with a real meaning, because names like this are called dunder methods, and Python calls them for you at specific moments. You never invoke __init__ yourself in normal code, because the constructor does it for you.
There is no keyword like new in Python. Book(...) is a plain function call, which is why a class can be called with the same syntax as any other callable. The name that you give the class becomes the name of that function, and the object that it produces is an instance of the type that the class defines.
Do two objects built from one class share data?
No, and this is the point that is worth proving early. Every instance gets its own attribute storage. Change title on one book and the other book is untouched, even though both of them were built by the same Book class.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
first = Book('Dune', 'Frank Herbert', 412)
second = Book('Piranesi', 'Susanna Clarke', 272)
first.title = 'Dune (anniversary edition)'
print('first :', first.title)
print('second:', second.title)
print('same object?', first is second)
print('instance storage:', vars(first))
Internally, that per-object storage is a plain dictionary that is called the instance __dict__. You can look at it directly, and it is a genuinely useful debugging tool. When an object is not behaving in the way you expected, printing vars(obj) or obj.__dict__ tells you exactly what state it believes it is in.
That dictionary belongs to one instance, and it is created empty for you the moment the object exists. Nothing about it is shared with the class or with any other object, which is why changing it cannot have side effects somewhere else. If you have ever wondered whether assigning to obj.x in one place could surprise you in another, the answer is no, as long as the assignment goes through an instance.
How do you check what an object is at runtime?
Three tools cover almost every case. type(obj) gives you the class itself. isinstance(obj, SomeClass) answers yes or no, and it accepts a tuple of classes when you want an "any of these" test. vars(obj) gives you the instance dictionary.
class Book:
def __init__(self, title):
self.title = title
class Paperback(Book):
pass
item = Paperback('The Dispossessed')
print('type :', type(item))
print('isinstance of Book :', isinstance(item, Book))
print('type is Book exactly :', type(item) is Book)
print('instance dict :', vars(item))
public = []
for name in dir(item):
if not name.startswith('_'):
public.append(name)
print('methods you can call :', public)
isinstance is the one to reach for, because it respects inheritance. A Paperback is a Book, so isinstance(paperback, Book) is True even though type(paperback) is Book is False. When you write code that should accept "a book or a magazine", then isinstance says what you mean, while a type() comparison says something stricter and usually wrong.
dir(obj) lists everything that you can reach on an object, which means its attributes, its methods, and the dunder methods that Python uses behind the scenes. It is a good way to discover what a library object actually supports.
When is a class better than a plain dictionary?
A dictionary holds data and nothing else. Every operation on it is a raw key lookup or a raw assignment, and nothing stops a typo from creating a brand new key where you meant to read an old one.
A class adds three things. It gives a name to the shape of the data, it provides methods that guarantee that the shape stays valid, and it gives you a type that you can check with isinstance. When the data has rules, such as a price that cannot be negative or a title that cannot be empty, you can enforce those rules in one place inside __init__, and every object built from that class inherits the guarantee.
def make_dict_book(title, pages):
return {'title': title, 'pages': pages, 'summary': lambda: f"{title} ({pages} pages)"}
class Book:
def __init__(self, title, pages):
if not title.strip():
raise ValueError('title cannot be blank')
if pages <= 0:
raise ValueError('pages must be positive')
self.title = title
self.pages = pages
def summary(self):
return f"{self.title} ({self.pages} pages)"
print(make_dict_book('Dune', 412)['summary']())
print(Book('Dune', 412).summary())
try:
Book('Dune', 0)
except ValueError as exc:
print('rejected:', exc)
None of this means that you should reach for a class on every bag of data. A dictionary is the right tool for a group of unrelated values where nothing needs to be true. Reach for a class when the values belong together and when you want the language to help you keep them consistent.
| You need | Reach for |
|---|---|
| a bag of unrelated values, with no rules | a plain dictionary |
| related values with rules that must hold | a class |
| the same shape repeated many times | a dataclass, which is lesson 49 |
| a set of values drawn from a fixed list | a plain string or an enum |
The short version
- A class defines a type, and calling it creates an instance with its own attribute storage.
__init__(self, ...)runs automatically at construction time, andselfis the new instance that Python passes in for you.- An assignment inside a method uses
self.name = valueto attach state to that one object. - Use
isinstance()for type checks so that inheritance still counts, and usevars(obj)to see the state of an object. - Use a class when data belongs together and has rules, and use a dictionary when it does not.
Try it yourself: model a small library
Write a Magazine class with title, issue_number, and month. Make __init__ refuse a negative issue number by raising ValueError. Add a label() method that returns something like "Magazine 12, published in March".
Then build a Library class that keeps a list of magazines in self.items, with methods to add an item, to count the items, and to list their labels. Test it by creating three magazines, checking that len(library.items) is 3, and confirming that creating a magazine with an issue number of 0 or -4 raises the error that you wrote. Print vars(library) at the end to see everything that the object is carrying.