Say we want to provide an abstraction of an "account" in a bank. Here's one approach, using a function
object in Python:
def account():
"""Return a dispatch dictionary representing a bank account.
>>> a = account()
>>> a['deposit'](100)
100
>>> a['withdraw'](90)
10
>>> a['withdraw'](90)
'Insufficient funds'
>>> a['balance']
10
"""
def withdraw(amount):
if amount > dispatch['balance']:
return 'Insufficient funds'
dispatch['balance'] -= amount
return dispatch['balance']
def deposit(amount):
dispatch['balance'] += amount
return dispatch['balance']
dispatch = {'balance': 0,
'withdraw': withdraw,
'deposit': deposit}
return dispatch
Here's another approach using type abstraction (i.e., class
keyword in Python):
class Account(object):
"""A bank account has a balance and an account holder.
>>> a = Account('John')
>>> a.deposit(100)
100
>>> a.withdraw(90)
10
>>> a.withdraw(90)
'Insufficient funds'
>>> a.balance
10
"""
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
def deposit(self, amount):
"""Add amount to balance."""
self.balance = self.balance + amount
return self.balance
def withdraw(self, amount):
"""Subtract amount from balance if funds are available."""
if amount > self.balance:
return 'Insufficient funds'
self.balance = self.balance - amount
return self.balance
My teacher started the topic "Object oriented programming" by introducing the class
keyword, and showing us these bullet points:
Object-oriented programming
A method for organizing modular programs:
- Abstraction barriers
- Message passing
- Bundling together information and related behavior
Do you think the first approach would suffice to satisfy the above definition? If yes, why do we need the class
keyword to do object-oriented programming?
class
does a similar optimization).foo.bar()
is usually identical tofoo['bar']()
, and on rare occasions the latter syntax is actually useful.object['method'](args)
, Python objects actually do the equivalent ofobject['method'](object, args)
. This becomes relevant when a base class calls methods in a child class, e.g. in the Strategy Pattern.