Classes and objects are the foundation of Object-Oriented Programming (OOP) in Python. They help you model real-world entities in code by grouping data and related behavior together. If you're building anything beyond a basic script, understanding how to define and use classes and objects is essential.
1. What is a Class?
A class is a blueprint for creating objects. It defines the structure (attributes) and behavior (methods) that the objects created from it will have.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}."
2. What is an Object?
An object is an instance of a class. You create an object by calling the class like a function.
person1 = Person("Alice", 30)
print(person1.greet())
Output:
Hello, my name is Alice.
3. The __init__()
Method
The __init__()
method is called automatically when a new object is created. It initializes the object's attributes.
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
4. Creating Multiple Objects
You can create multiple objects from the same class, each with its own attribute values.
car1 = Car("Toyota", 2020)
car2 = Car("Honda", 2022)
print(car1.brand) # Toyota
print(car2.brand) # Honda
5. Adding Methods to a Class
Methods are functions defined inside a class. They operate on the instance of the class.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rect = Rectangle(4, 5)
print(rect.area()) # Output: 20
6. Attributes vs Methods
- Attributes: Variables associated with an object (e.g.,
self.name
) - Methods: Functions defined in a class that can act on object data
7. Using self
Keyword
The self
parameter represents the current object. It's how Python knows which object’s attributes or methods to access.
class Book:
def __init__(self, title):
self.title = title
def display_title(self):
return f"The book title is {self.title}"
8. Modifying Object Attributes
book = Book("Python Basics")
print(book.display_title())
book.title = "Advanced Python"
print(book.display_title())
Output:
The book title is Python Basics The book title is Advanced Python
9. Deleting Attributes and Objects
del book.title # Deletes attribute
del book # Deletes object
Be cautious: deleting an object removes it from memory.
10. Summary
- A class is a blueprint for creating objects
- An object is an instance of a class
- Use
__init__()
to initialize object attributes - Use
self
to refer to instance-specific data - Methods define behaviors that belong to the class
- Objects can have their attributes updated or removed
11. Final Thoughts
Understanding how to use classes and objects is a key step in mastering Python. They make your code more modular, reusable, and closer to real-world problem-solving. Once you're comfortable with the basics, you'll be ready to explore advanced OOP concepts like inheritance, polymorphism, and encapsulation.