Understanding classes, objects, and the foundations of OOP in Python
Object‑oriented programming (OOP) is a programming paradigm based on the concept of “objects” — data structures that contain both data (attributes) and behavior (methods). Python supports OOP and uses it extensively in real‑world applications.
A class is a blueprint for creating objects. An object is an instance of a class.
class Person:
pass
p = Person()
print(p)
Attributes store data, and methods define behavior.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(p.name) # Alice
print(p.age) # 30
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, I'm {self.name}!")
p = Person("Bob")
p.greet()
__init__ is a special method that runs automatically when an object is created. It initializes the object’s attributes.
self refers to the current instance of the class. It must be the first parameter of every method inside a class.
Encapsulation means bundling data and methods inside a class. Python uses naming conventions to indicate private attributes:
class BankAccount:
def __init__(self, balance):
self._balance = balance # "protected" by convention
Instance attributes belong to each object. Class attributes are shared across all objects.
class Dog:
species = "Canine" # class attribute
def __init__(self, name):
self.name = name # instance attribute
d1 = Dog("Rex")
d2 = Dog("Buddy")
print(d1.species) # Canine
print(d2.species) # Canine
Now that you understand the basics of OOP, you're ready to explore inheritance and more advanced class features in Lesson 13: Classes, Objects, and Inheritance.
← Back to Lesson Index