Introduction to Object-Oriented Programming (OOP)
Overview
Object-Oriented Programming (OOP) is a style of programming, not a language-specific feature. It is implemented in many languages including Python, Java, and C++. The core principles are transferable across languages — only the syntax changes.
Key Insight: You've Already Been Using OOP
Everything in Python is an object. Even basic data types like integers, strings, and lists are objects — instances of their respective classes.
x = 1 # Object of type int
y = "hello" # Object of type str
z = [1, 2, 3] # Object of type list
Core Principles
1. Objects
An object is a piece of data in your program. Every value you create is an object.
- Objects have a type (also called a class)
- The type defines how the object can behave and interact with other objects
print(type(x)) # <class 'int'>
print(type(y)) # <class 'str'>
print(type(z)) # <class 'list'>
Even functions are objects! ```python def funk(): print("Hello")
print(type(funk)) #
```
2. Classes
A class is a blueprint that defines the behavior of all objects of that type.
int,float,str,list,dict,set,bool— these are all classes- The class determines what operations and methods are valid for its instances
# Why this works:
x + 2 # int + int ✅
# Why this fails:
x + y # int + str ❌ → TypeError: unsupported operand type(s)
3. Instances
An instance is a specific object created from a class. Every time you create a value, you're creating an instance.
x = 1 # Instance of class int, value = 1
x2 = 2 # Another instance of class int, value = 2
# x and x2 are separate, distinct objects
Multiple instances of the same class can exist independently of each other.
4. Methods
A method is a function that belongs to a class and is called on an instance using the dot (.) operator.
st = "hello"
st.upper() # Method on str instance → "HELLO"
st.lower() # Method on str instance → "hello"
nums = [3, 1, 2]
nums.index(1) # Method on list instance → 1
Why does .upper() work on strings but not ints?
Because the str class defines the .upper() method, while the int class does not.
x = 1
x.upper() # ❌ AttributeError: 'int' object has no attribute 'upper'
Terminology Summary
| Term | Definition |
|---|---|
| Object | A piece of data in a program; an instance of a class |
| Class | A blueprint defining the behavior of all objects of a given type |
| Instance | A specific object created from a class |
| Method | A function defined by a class, called on an instance using . |
| Type | The class an object belongs to (e.g. int, str, list) |
Key Takeaways & Recap
- OOP is a programming paradigm — concepts apply across many languages
- In Python, everything is an object (numbers, strings, lists, even functions)
- The class of an object defines what it can do
- You create instances of classes whenever you define a variable
- Methods are functions tied to specific class types