Level: Intermediate | Prerequisite: Week 6
Learning Goals
- Define classes and create instances
- Understand the meaning of constructors and destructors
- Work with instance methods and attributes
- Encapsulation conventions (private, protected)
1. What is a class
A blueprint that combines data (attributes) and behaviors (methods). An instance (object) is created based on this.
class Account:
def __init__(self, owner, balance=0):
self.owner = owner #Instance Properties
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("Insufficient balance")
self.balance -= amount
a = Account("Hong Gil-dong", 1000) #Create Instance
a.deposit(500)
print(a.balance) # 1500
2. Meaning of self
The first argument of a method is always self — the instance itself that was called.
a = Account("Hong Gil-dong")
a.deposit(100) #In reality, Account.deposit(a, 100)
Through self, access instance attributes.
3. Instance variables vs Class variables
class Counter:
total = 0 #Class variable — shared by all instances
def __init__(self):
Counter.total += 1
self.id = Counter.total #Instance variable — each is different
c1 = Counter()
c2 = Counter()
print(c1.id, c2.id, Counter.total) # 1 2 2
4. Encapsulation conventions
Python has no true private. Represented by convention:
- _single_underscore — "internal use" (signal not to use externally)
- __double_underscore — name mangling (converted to _ClassName__attribute)
class Account:
def __init__(self, owner, balance):
self._owner = owner #For internal use
self.__balance = balance # name mangled
def get_balance(self):
return self.__balance
a = Account("Hong Gil-dong", 1000)
print(a._owner) #Possible (refrain as a convention)
# print(a.__balance) # AttributeError
print(a._Account__balance) #Operation is possible (not recommended)
5. Object comparison
Default equality compares whether objects are the same (using id). For semantic comparison, override eq (next week).
Key Examples (examples/)
| File | Content |
|---|---|
| Class definition & instance | |
| Behavior of self | |
| Class variables vs Instance variables | |
| Encapsulation conventions |
⚠️ Common Mistakes
- Omitting
self—def deposit(amount):→ An instance is automatically created, but if there are no parameters, TypeError occurs. - Mutable object as a class variable — Shared by all instances, which can unintentionally change together.
class Bag: items = [] #Danger!
→ Inside __init__, self.items = [].
3. Using an attribute with a different name in __init__ — Attribute missing due to a typo.
❓ FAQ
Q1. Do all codes have to be written as classes? A. No. Only when state + behavior should be bound together to make sense. Use simple functions if they are clearer.
Q2. Other magic methods besides __init__?
A. In the next week, we will study __str__, __eq__, __len__, etc.
Q3. Naming convention for class names?
A. PascalCase (BankAccount, UserProfile). Functions and variables use snake_case.
📝 Exercises (exercises/)
exercise1.md—BankAccountclassexercise2.md—Stackclassexercise3.md—Studentclass (Score Average/Highest)
Next Week
Week 8. Object-Oriented (2) — Inheritance · Polymorphism