Skip to content

Commit

Permalink
2.6
Browse files Browse the repository at this point in the history
  • Loading branch information
wizardforcel committed Sep 2, 2016
1 parent 75cef93 commit a4126e8
Showing 1 changed file with 187 additions and 0 deletions.
187 changes: 187 additions & 0 deletions 2.6.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
# 2.6 实现类和对象

> 来源:[2.6 Implementing Classes and Objects](http://www-inst.eecs.berkeley.edu/~cs61a/sp12/book/objects.html#implementing-classes-and-objects)
> 译者:[飞龙](https://github.com/wizardforcel)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
在使用面向对象编程范式时,我们使用对象隐喻来指导程序的组织。数据表示和操作的大部分逻辑都表达在类的定义中。在这一节中,我们会看到,类和对象本身可以使用函数和字典来表示。以这种方式实现对象系统的目的是展示使用对象隐喻并不需要特殊的编程语言。即使编程语言没有面向对象系统,程序照样可以面向对象。

为了实现对象,我们需要抛弃点运算符(它需要语言的内建支持),并创建分发字典,它的行为和内建对象系统的元素差不多。我们已经看到如何通过分发字典实现消息传递行为。为了完整实现对象系统,我们需要在实例、类和基类之间发送消息,它们全部都是含有属性的字典。

我们不会实现整个 Python 对象系统,它包含这篇文章没有涉及到的特性(比如元类和静态方法)。我们会专注于用户定义的类,不带有多重继承和内省行为(比如返回实例的类)。我们的实现并不遵循 Python 类型系统的明确规定。反之,它为实现对象隐喻的核心功能而设计。

## 2.6.1 实例

我们从实例开始。实例拥有具名属性,例如账户余额,它可以被设置或获取。我们使用分发字典来实现实例,它会响应“get”和“set”属性值消息。属性本身保存在叫做`attributes`的局部字典中。

就像我们在这一章的前面看到的那样,字典本身是抽象数据类型。我们使用列表来实现字典,我们使用偶对来实现列表,并且我们使用函数来实现偶对。就像我们以字典实现对象系统那样,要注意我们能够仅仅使用函数来实现对象。

为了开始我们的实现,我们假设我们拥有一个类实现,它可以查找任何不是实例部分的名称。我们将类作为参数`cls`传递给`make_instance`

```py
>>> def make_instance(cls):
"""Return a new object instance, which is a dispatch dictionary."""
def get_value(name):
if name in attributes:
return attributes[name]
else:
value = cls['get'](name)
return bind_method(value, instance)
def set_value(name, value):
attributes[name] = value
attributes = {}
instance = {'get': get_value, 'set': set_value}
return instance
```

`instance`是分发字典,它响应消息`get``set``set`消息对应 Python 对象系统的属性赋值:所有赋值的属性都直接储存在对象的局部属性字典中。在`get`中,如果`name`在局部`attributes`字典中不存在,那么它会在类中寻找。如果`cls`返回的`value`为函数,它必须绑定到实例上。

**绑定方法值。**`make_instance`中的`get_value `使用`get`寻找类中的具名属性,之后调用`bind_method`。方法的绑定只在函数值上调用,并且它会通过将实例插入为第一个参数,从函数值创建绑定方法的值。

```py
>>> def bind_method(value, instance):
"""Return a bound method if value is callable, or value otherwise."""
if callable(value):
def method(*args):
return value(instance, *args)
return method
else:
return value
```

当方法被调用时,第一个参数`self`通过这个定义绑定到了`instance`的值上。

## 2.6.2 类

类也是对象,在 Python 对象系统和我们这里实现的系统中都是如此。为了简化,我们假设类自己并没有类(在 Python 中,类本身也有类,几乎所有类都共享相同的类,叫做`type`)。类可以接受`get``set`消息,以及`new`消息。

```py
>>> def make_class(attributes, base_class=None):
"""Return a new class, which is a dispatch dictionary."""
def get_value(name):
if name in attributes:
return attributes[name]
elif base_class is not None:
return base_class['get'](name)
def set_value(name, value):
attributes[name] = value
def new(*args):
return init_instance(cls, *args)
cls = {'get': get_value, 'set': set_value, 'new': new}
return cls
```

不像实例那样,类的`get`函数在属性未找到的时候并不查询它的类,而是查询它的`base_class`。类并不需要方法绑定。

**实例化。**`make_class `中的`new`函数调用了`init_instance`,它首先创建新的实例,之后调用叫做`__init__`的方法。

```py
>>> def init_instance(cls, *args):
"""Return a new object with type cls, initialized with args."""
instance = make_instance(cls)
init = cls['get']('__init__')
if init:
init(instance, *args)
return instance
```

最后这个函数完成了我们的对象系统。我们现在拥有了实例,它的`set`是局部的,但是`get`会回溯到它们的类中。实例在它的类中查找名称之后,它会将自己绑定到函数值上来创建方法。最后类可以创建新的(`new`)实例,并且在实例创建之后立即调用它们的`__init__`构造器。

在对象系统中,用户仅仅可以调用`create_class`,所有其他功能通过消息传递来使用。与之相似,Python 的对象系统由`class`语句来调用,它的所有其他功能都通过点表达式和对类的调用来使用。

## 2.6.3 使用所实现的对象

我们现在回到上一节银行账户的例子。使用我们实现的对象系统,我们就可以创建`Account`类,`CheckingAccount`子类和它们的实例。

`Account`类通过`create_account_class `函数创建,它拥有类似于 Python `class`语句的结构,但是以`make_class`的调用结尾。

```py
>>> def make_account_class():
"""Return the Account class, which has deposit and withdraw methods."""
def __init__(self, account_holder):
self['set']('holder', account_holder)
self['set']('balance', 0)
def deposit(self, amount):
"""Increase the account balance by amount and return the new balance."""
new_balance = self['get']('balance') + amount
self['set']('balance', new_balance)
return self['get']('balance')
def withdraw(self, amount):
"""Decrease the account balance by amount and return the new balance."""
balance = self['get']('balance')
if amount > balance:
return 'Insufficient funds'
self['set']('balance', balance - amount)
return self['get']('balance')
return make_class({'__init__': __init__,
'deposit': deposit,
'withdraw': withdraw,
'interest': 0.02})
```

在这个函数中,属性名称在最后设置。不像 Python 的`class`语句,它强制内部函数和属性名称之间的一致性。这里我们必须手动指定属性名称和值的对应关系。

`Account`类最终由赋值来实例化。

```py
>>> Account = make_account_class()
```

之后,账户实例通过`new`消息来创建,它需要名称来处理新创建的账户。

```py
>>> jim_acct = Account['new']('Jim')
```

之后,`get`消息传递给`jim_acct `,来获取属性和方法。方法可以调用来更新账户余额。

```py
>>> jim_acct['get']('holder')
'Jim'
>>> jim_acct['get']('interest')
0.02
>>> jim_acct['get']('deposit')(20)
20
>>> jim_acct['get']('withdraw')(5)
15
```

就像使用 Python 对象系统那样,设置实例的属性并不会修改类的对应属性:

```py
>>> jim_acct['set']('interest', 0.04)
>>> Account['get']('interest')
0.02
```

**继承。**我们可以创建`CheckingAccount`子类,通过覆盖类属性的子集。在这里,我们修改`withdraw`方法来收取费用,并且降低了利率。

```py
>>> def make_checking_account_class():
"""Return the CheckingAccount class, which imposes a $1 withdrawal fee."""
def withdraw(self, amount):
return Account['get']('withdraw')(self, amount + 1)
return make_class({'withdraw': withdraw, 'interest': 0.01}, Account)
```

在这个实现中,我们在子类的`withdraw `中调用了基类`Account``withdraw`函数,就像在 Python 内建对象系统那样。我们可以创建子类本身和它的实例,就像之前那样:

```py
>>> CheckingAccount = make_checking_account_class()
>>> jack_acct = CheckingAccount['new']('Jack')
```

它们的行为相似,构造函数也一样。每笔取款都会在特殊的`withdraw`函数中收费 $1,并且`interest`也拥有新的较低值。

```py
>>> jack_acct['get']('interest')
0.01
>>> jack_acct['get']('deposit')(20)
20
>>> jack_acct['get']('withdraw')(5)
14
```

我们的构建在字典上的对象系统十分类似于 Python 内建对象系统的实现。Python 中,任何用户定义类的实例,都有个特殊的`__dict__`属性,将对象的局部实例属性储存在字典中,就像我们的`attributes`字典那样。Python 的区别在于,它区分特定的特殊方法,这些方法和内建函数交互来确保那些函数能正常处理许多不同类型的参数。操作不同类型参数的函数是下一节的主题。

0 comments on commit a4126e8

Please sign in to comment.