假设我们要提供银行“帐户”的抽象。这是function
在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
这是使用类型抽象(即class
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
我的老师通过引入class
关键字并向我们展示了这些要点,开始了主题“面向对象的编程” :
面向对象编程
一种组织模块化程序的方法:
- 抽象壁垒
- 讯息传递
- 将信息和相关行为捆绑在一起
您认为第一种方法足以满足上述定义吗?如果是,为什么我们需要class
关键字来进行面向对象的编程?
foo.bar()
通常与相同foo['bar']()
,在极少数情况下,后一种语法实际上很有用。
class
做了类似的优化)。