Phase: 5. OOP | Estimated time: 2 hours | Milestone Project: No
- Module 041 (Introduction to OOP)
By the end of this module, you will be able to:
- Define instance attributes using
self.attr - Write methods — functions defined inside a class
- Call methods on an instance
- Use
__init__to initialize attributes - Add and change attributes dynamically
- Distinguish between a method and a standalone function
Attributes store an object's data; methods define what an object can do. Together they form the core of every class you'll ever write.
Attributes are pieces of data attached to an instance. They are created by assigning to self inside methods (usually __init__).
class Student:
"""Represent a student."""
def __init__(self, name, student_id):
"""Initialize student attributes."""
self.name = name
self.student_id = student_id
self.courses = [] # default valueA method is a function defined inside a class. The first parameter is always self.
class Student:
"""Represent a student."""
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
self.courses = []
def enroll(self, course):
"""Enroll the student in a course."""
self.courses.append(course)
def display_info(self):
"""Show student info."""
info = f"{self.name} (ID: {self.student_id})\nEnrolled: {', '.join(self.courses) if self.courses else 'None'}"
return infoalice = Student("Alice", "S1001")
alice.enroll("Python 101")
alice.enroll("Data Structures")
print(alice.display_info())
# Alice (ID: S1001)
# Enrolled: Python 101, Data StructuresPython objects are flexible — you can add attributes after creation:
alice.gpa = 3.8 # new attribute added on the fly
alice.name = "Alice B." # existing attribute changedThis flexibility is powerful but can lead to bugs — __init__ documents what attributes an instance should have.
| Aspect | Function | Method |
|---|---|---|
| Defined | Standalone with def |
Inside a class with def |
| First parameter | Any parameters | self (the instance) |
| Called on | Directly | instance.method() |
| Access to instance | No | Yes, via self |
def greet(name): # function
return f"Hello {name}"
class Person:
def greet(self): # method
return f"Hello {self.name}"- Forgetting
selfin method definition: Causes aTypeErrorwhen called. - Omitting parentheses in method call:
obj.methodreturns the method object, doesn't call it. - Using class name instead of
self: Always refer to instance attributes viaself. - Assuming attribute exists: Check with
hasattr()or usegetattr(obj, attr, default).
- Write a
class BankAccountwith__init__that setsownerandbalance. - Add methods
deposit(amount)andwithdraw(amount). - Create an account, deposit 100, withdraw 30, and print the balance.
- Add a new attribute
account_typedynamically after creation.
- Attributes store data; methods define behavior.
- Use
self.attr = valueinside__init__to initialize attributes. - Methods are called on an instance:
instance.method(). - Python lets you add attributes dynamically, but
__init__is the canonical place. - Methods are functions that belong to a specific class instance.
Continue to Module 043: Constructors (__init__) and self.