Classes & Objects
Overview
Classes are blueprints for creating objects. Objects bundle data variables and functions together.
Learning Objectives
- Define custom classes with init constructors.
- Understand the 'self' parameter in class methods.
- Instantiate objects and access their attributes.
Concept Explanation
A class is a template. The __init__ constructor initializes new object instances. The self parameter references the current object instance, letting you access and modify its variables.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
class User:
def __init__(self, name):
self.name = name
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def describe(self):
return f'{self.title} by {self.author}'
my_book = Book('1984', 'George Orwell')
print(my_book.describe())
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
class BankAccount:
def __init__(self, owner, balance=0.0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
print('Amount must be positive')
return
self.balance += amount
print(f'Deposited {amount}. Balance: {self.balance}')
account = BankAccount('Alex', 100.0)
account.deposit(50.0)
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Declare Class → Call constructor class name → Run __init__ → Bind attributes to self → Return object reference
Common Mistakes
Review these common pitfalls when working with this topic:
- Forgetting to write the 'self' parameter in class method definitions.
- Confusing class-level variables (shared by all instances) with instance variables (unique to each object).
- Invoking class methods without parentheses.
- Using lowercase class names (naming classes using CapitalCamelCase is standard).
Best Practices
Enforce these Pythonic best practices in your codebase:
class employee:
def setup(emp, n):
emp.name = n # Missing standard init
class Employee:
def __init__(self, name):
self.name = name # Correct initializer
Quick Revision
Use these key summaries for last-minute revision:
- class defines a new blueprint schema.
- init method initializes object attributes.
- self represents the current object instance.
- Methods are functions defined inside classes.
- Access variables using object.attribute.