Python Classes and Objects
Classes and Objects
Python follows the object-oriented programming (OOP) paradigm. In Python, almost everything is an object — numbers, strings, lists, functions, and the objects you create from your own classes. Every object can contain:
- Attributes — data stored in the object
- Methods — functions that belong to the object and define its behavior
A class is the template, or blueprint, used to create objects. This lesson shows how to define a class, create objects from it, access their attributes, and delete them.
Creating a Class
Define a class with the class keyword, followed by the class name and a colon. The class body is indented.
Syntax
class ClassName:
# class body: attributes and methods
By convention, class names use PascalCase — each word starts with a capital letter, with no underscores: Book, BankAccount, StudentRecord.
Example: Defining a Simple Class
class Book:
pages = 250
Bookis the class.pagesis a class attribute — a variable defined directly in the class body. Every object created fromBookcan access it.
Defining a class does not create any objects yet; it only describes what Book objects will look like.
Creating Objects From a Class
To create an object, write the class name followed by parentheses. This is called instantiating the class, and the resulting object is called an instance.
Example: Creating an Object and Accessing an Attribute
class Book:
pages = 250
my_book = Book()
print(my_book.pages)
Expected output:
250
Book()creates a newBookobject, which is stored inmy_book.my_book.pagesuses dot notation to access thepagesattribute of the object.
You can confirm which class an object belongs to:
print(type(my_book))
print(isinstance(my_book, Book))
Expected output:
<class '__main__.Book'>
True
Creating Multiple Objects
You can create any number of objects from the same class. Each one is a separate instance, but all follow the same class structure.
Example: Multiple Objects From One Class
class Book:
pages = 250
book1 = Book()
book2 = Book()
book3 = Book()
print(book1.pages)
print(book2.pages)
print(book3.pages)
Expected output:
250
250
250
All three objects read the same class attribute, so they all show 250.
print(book1 is book2)
Expected output:
False
Even though they look identical, book1 and book2 are two different objects in memory.
Object Independence
Objects created from the same class are independent. Giving one object its own value does not affect the others.
class Book:
pages = 250
book1 = Book()
book2 = Book()
book1.pages = 400
print(book1.pages)
print(book2.pages)
print(Book.pages)
Expected output:
400
250
250
What happened: book1.pages = 400 created a new attribute on book1 only. That instance attribute now hides the class attribute for book1. book2 still reads the shared class attribute, which is unchanged.
Shared Class Attributes
The exception is when the class attribute itself is changed. Then every object that does not have its own value sees the change:
class Book:
pages = 250
book1 = Book()
book2 = Book()
Book.pages = 300
print(book1.pages)
print(book2.pages)
Expected output:
300
300
Class attributes are shared by design. They are useful for values that should be the same for all objects, such as a tax rate or a company name. Values that differ per object — a book's title, a student's marks — should be instance attributes, which are usually set in the __init__() method covered in the next lesson.
Adding Methods to a Class
A method is a function defined inside a class. Methods describe what objects of the class can do.
class Book:
pages = 250
def describe(self):
print(f"This book has {self.pages} pages.")
novel = Book()
novel.describe()
Expected output:
This book has 250 pages.
describe()is defined inside the class, so everyBookobject can use it.selfrefers to the object the method was called on — here,novel. It is explained in detail in the Python self Parameter lesson.
Deleting Objects
The del keyword deletes a name (variable) that refers to an object.
Example: Deleting an Object Reference
class Book:
pages = 250
device = Book()
del device
print(device)
Output:
NameError: name 'device' is not defined
After del device, the name device no longer exists, so using it raises a NameError.
How it works internally:
delremoves the variable, not necessarily the object. Python automatically frees an object's memory when no variables refer to it any more. If another variable still points to the same object, the object survives:a = Book() b = a del a print(b.pages) # The object still exists through b — prints 250
You can also delete an attribute from an object: del novel.pages removes the instance attribute pages if the object has one.
The pass Statement in Classes
A class body cannot be empty. If you need a class with no content yet — for planning or future use — use pass.
Example: An Empty Class
class Employee:
pass
e = Employee()
print(type(e))
Expected output:
<class '__main__.Employee'>
Even an empty class can create objects, and you can attach attributes to those objects later.
Practical Example: A Product Class
class Product:
currency = "INR" # Shared by all products
def show(self):
print(f"{self.name}: {self.price} {self.currency}")
p1 = Product()
p1.name = "Notebook"
p1.price = 45
p2 = Product()
p2.name = "Backpack"
p2.price = 899
p1.show()
p2.show()
Expected output:
Notebook: 45 INR
Backpack: 899 INR
Each product has its own name and price, while currency is shared through the class. Assigning attributes one by one after creating each object works, but it is repetitive and easy to get wrong — the next lesson shows how __init__() sets them automatically.
Common Mistakes
| Mistake | Problem |
|---|---|
my_book = Book (no parentheses) | Refers to the class, not a new object |
| Accessing an attribute that was never set | AttributeError |
Expecting obj.attr = value to change all objects | It changes only that object |
| Using mutable class attributes such as lists for per-object data | All objects share and modify the same list |
Forgetting self in a method definition | TypeError when the method is called |
Related Concepts
- Python OOP — the concepts behind classes and objects
- Python
__init__()Method — initializing objects with their own data - Python self Parameter — how methods refer to their object
- Python Class Properties and Class Methods — attributes and behaviors in depth