Object-oriented programming (OOP) models program concepts as objects. An object keeps data together with behavior that operates on that data. A class describes shared structure and behavior; each object is an instance created from that template.
🏠 Blueprint → housesOne blueprint creates houses with different addresses and colors.
🍪 Cutter → cookiesThe cutter defines a shape, while every cookie is independent.
📝 Account form → accountsFields and rules are shared; every account has its own owner and balance.
Classes, objects, attributes, and methods
Attributes describe what an object has; methods describe what it can do. Objects share method code, while self directs that code to the current object.
class BankAccount:
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
account = BankAccount()
account.owner = "Alice"
account.account = "6250941006528599"
account.balance = 50
account.deposit(100)
print(account.balance)Account object factory: one blueprint, independent state
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Encapsulation and valid state
If arbitrary outside code can make a balance negative, the account enters an invalid state. Encapsulation is not secrecy; it funnels changes through operations such as deposit() and withdraw(), where rules can be checked. Double-underscore names trigger name mangling to reduce accidental outside access. This is a design mechanism, not security encryption.
The constructor
__init__() runs automatically for a new object. It gathers required values at construction time so every instance begins with complete, valid state.
class BankAccount:
def __init__(self, owner, account, balance):
self.__owner = owner
self.__account = account
self.__balance = balance
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount <= 0:
return False
self.__balance += amount
return True
def withdraw(self, amount):
if amount <= 0 or amount > self.__balance:
return False
self.__balance -= amount
return TrueConstructor and private state: four steps to a valid object
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Create three independent student objects
- Define Student with name and score constructor parameters.
- Implement add_score(points).
- Create three objects with different scores, add 5 to only one, then print all scores.
Build a safe bank account
- Store balance as a private attribute.
- Let deposit accept only positive values.
- Reject non-positive withdrawals and overdrafts.
- Perform two valid operations and one failed operation; print results and balance.
Encapsulate a thermometer
- Thermometer stores Celsius in a private field.
- set_celsius rejects values below -273.15.
- Provide get_celsius() and get_fahrenheit().
- Test one valid and one invalid value.