8.1 Classes, Objects, and Encapsulation
Object-oriented programming, or OOP, models things as objects. An object stores data and provides behavior. A class is a template, and an object is an instance of that class.
Classes and Objects
The BankAccount class below represents a bank account. owner, account, and balance are attributes. deposit() and withdraw() are methods.
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("Balance:", account.balance)Output:
Balance: 150Here, self means the current object. When account.deposit(100) runs, self refers to account.
Encapsulation
Encapsulation hides internal implementation details and lets outside code access or change state through clear methods.
If account balance can be changed freely from outside, it is hard to keep data valid. A better design makes balance private and checks changes through methods.
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 TruePrivate attributes are not meant to make code mysterious. They keep state changes inside trusted methods.
Constructor
__init__() is the constructor. It runs automatically when an object is created.
account = BankAccount("Alice", "6250941006528599", 50)Constructors are commonly used to set initial object state. If an object should always have certain attributes, initialize them in __init__().