|
| 1 | +# 2.6 实现类和对象 |
| 2 | + |
| 3 | +> 来源:[2.6 Implementing Classes and Objects](http://www-inst.eecs.berkeley.edu/~cs61a/sp12/book/objects.html#implementing-classes-and-objects) |
| 4 | +
|
| 5 | +> 译者:[飞龙](https://github.com/wizardforcel) |
| 6 | +
|
| 7 | +> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) |
| 8 | +
|
| 9 | +在使用面向对象编程范式时,我们使用对象隐喻来指导程序的组织。数据表示和操作的大部分逻辑都表达在类的定义中。在这一节中,我们会看到,类和对象本身可以使用函数和字典来表示。以这种方式实现对象系统的目的是展示使用对象隐喻并不需要特殊的编程语言。即使编程语言没有面向对象系统,程序照样可以面向对象。 |
| 10 | + |
| 11 | +为了实现对象,我们需要抛弃点运算符(它需要语言的内建支持),并创建分发字典,它的行为和内建对象系统的元素差不多。我们已经看到如何通过分发字典实现消息传递行为。为了完整实现对象系统,我们需要在实例、类和基类之间发送消息,它们全部都是含有属性的字典。 |
| 12 | + |
| 13 | +我们不会实现整个 Python 对象系统,它包含这篇文章没有涉及到的特性(比如元类和静态方法)。我们会专注于用户定义的类,不带有多重继承和内省行为(比如返回实例的类)。我们的实现并不遵循 Python 类型系统的明确规定。反之,它为实现对象隐喻的核心功能而设计。 |
| 14 | + |
| 15 | +## 2.6.1 实例 |
| 16 | + |
| 17 | +我们从实例开始。实例拥有具名属性,例如账户余额,它可以被设置或获取。我们使用分发字典来实现实例,它会响应“get”和“set”属性值消息。属性本身保存在叫做`attributes`的局部字典中。 |
| 18 | + |
| 19 | +就像我们在这一章的前面看到的那样,字典本身是抽象数据类型。我们使用列表来实现字典,我们使用偶对来实现列表,并且我们使用函数来实现偶对。就像我们以字典实现对象系统那样,要注意我们能够仅仅使用函数来实现对象。 |
| 20 | + |
| 21 | +为了开始我们的实现,我们假设我们拥有一个类实现,它可以查找任何不是实例部分的名称。我们将类作为参数`cls`传递给`make_instance`。 |
| 22 | + |
| 23 | +```py |
| 24 | +>>> def make_instance(cls): |
| 25 | + """Return a new object instance, which is a dispatch dictionary.""" |
| 26 | + def get_value(name): |
| 27 | + if name in attributes: |
| 28 | + return attributes[name] |
| 29 | + else: |
| 30 | + value = cls['get'](name) |
| 31 | + return bind_method(value, instance) |
| 32 | + def set_value(name, value): |
| 33 | + attributes[name] = value |
| 34 | + attributes = {} |
| 35 | + instance = {'get': get_value, 'set': set_value} |
| 36 | + return instance |
| 37 | +``` |
| 38 | + |
| 39 | +`instance`是分发字典,它响应消息`get`和`set`。`set`消息对应 Python 对象系统的属性赋值:所有赋值的属性都直接储存在对象的局部属性字典中。在`get`中,如果`name`在局部`attributes`字典中不存在,那么它会在类中寻找。如果`cls`返回的`value`为函数,它必须绑定到实例上。 |
| 40 | + |
| 41 | +**绑定方法值。**`make_instance`中的`get_value `使用`get`寻找类中的具名属性,之后调用`bind_method`。方法的绑定只在函数值上调用,并且它会通过将实例插入为第一个参数,从函数值创建绑定方法的值。 |
| 42 | + |
| 43 | +```py |
| 44 | +>>> def bind_method(value, instance): |
| 45 | + """Return a bound method if value is callable, or value otherwise.""" |
| 46 | + if callable(value): |
| 47 | + def method(*args): |
| 48 | + return value(instance, *args) |
| 49 | + return method |
| 50 | + else: |
| 51 | + return value |
| 52 | +``` |
| 53 | + |
| 54 | +当方法被调用时,第一个参数`self`通过这个定义绑定到了`instance`的值上。 |
| 55 | + |
| 56 | +## 2.6.2 类 |
| 57 | + |
| 58 | +类也是对象,在 Python 对象系统和我们这里实现的系统中都是如此。为了简化,我们假设类自己并没有类(在 Python 中,类本身也有类,几乎所有类都共享相同的类,叫做`type`)。类可以接受`get`和`set`消息,以及`new`消息。 |
| 59 | + |
| 60 | +```py |
| 61 | +>>> def make_class(attributes, base_class=None): |
| 62 | + """Return a new class, which is a dispatch dictionary.""" |
| 63 | + def get_value(name): |
| 64 | + if name in attributes: |
| 65 | + return attributes[name] |
| 66 | + elif base_class is not None: |
| 67 | + return base_class['get'](name) |
| 68 | + def set_value(name, value): |
| 69 | + attributes[name] = value |
| 70 | + def new(*args): |
| 71 | + return init_instance(cls, *args) |
| 72 | + cls = {'get': get_value, 'set': set_value, 'new': new} |
| 73 | + return cls |
| 74 | +``` |
| 75 | + |
| 76 | +不像实例那样,类的`get`函数在属性未找到的时候并不查询它的类,而是查询它的`base_class`。类并不需要方法绑定。 |
| 77 | + |
| 78 | +**实例化。**`make_class `中的`new`函数调用了`init_instance`,它首先创建新的实例,之后调用叫做`__init__`的方法。 |
| 79 | + |
| 80 | +```py |
| 81 | +>>> def init_instance(cls, *args): |
| 82 | + """Return a new object with type cls, initialized with args.""" |
| 83 | + instance = make_instance(cls) |
| 84 | + init = cls['get']('__init__') |
| 85 | + if init: |
| 86 | + init(instance, *args) |
| 87 | + return instance |
| 88 | +``` |
| 89 | + |
| 90 | +最后这个函数完成了我们的对象系统。我们现在拥有了实例,它的`set`是局部的,但是`get`会回溯到它们的类中。实例在它的类中查找名称之后,它会将自己绑定到函数值上来创建方法。最后类可以创建新的(`new`)实例,并且在实例创建之后立即调用它们的`__init__`构造器。 |
| 91 | + |
| 92 | +在对象系统中,用户仅仅可以调用`create_class`,所有其他功能通过消息传递来使用。与之相似,Python 的对象系统由`class`语句来调用,它的所有其他功能都通过点表达式和对类的调用来使用。 |
| 93 | + |
| 94 | +## 2.6.3 使用所实现的对象 |
| 95 | + |
| 96 | +我们现在回到上一节银行账户的例子。使用我们实现的对象系统,我们就可以创建`Account`类,`CheckingAccount`子类和它们的实例。 |
| 97 | + |
| 98 | +`Account`类通过`create_account_class `函数创建,它拥有类似于 Python `class`语句的结构,但是以`make_class`的调用结尾。 |
| 99 | + |
| 100 | +```py |
| 101 | +>>> def make_account_class(): |
| 102 | + """Return the Account class, which has deposit and withdraw methods.""" |
| 103 | + def __init__(self, account_holder): |
| 104 | + self['set']('holder', account_holder) |
| 105 | + self['set']('balance', 0) |
| 106 | + def deposit(self, amount): |
| 107 | + """Increase the account balance by amount and return the new balance.""" |
| 108 | + new_balance = self['get']('balance') + amount |
| 109 | + self['set']('balance', new_balance) |
| 110 | + return self['get']('balance') |
| 111 | + def withdraw(self, amount): |
| 112 | + """Decrease the account balance by amount and return the new balance.""" |
| 113 | + balance = self['get']('balance') |
| 114 | + if amount > balance: |
| 115 | + return 'Insufficient funds' |
| 116 | + self['set']('balance', balance - amount) |
| 117 | + return self['get']('balance') |
| 118 | + return make_class({'__init__': __init__, |
| 119 | + 'deposit': deposit, |
| 120 | + 'withdraw': withdraw, |
| 121 | + 'interest': 0.02}) |
| 122 | +``` |
| 123 | + |
| 124 | +在这个函数中,属性名称在最后设置。不像 Python 的`class`语句,它强制内部函数和属性名称之间的一致性。这里我们必须手动指定属性名称和值的对应关系。 |
| 125 | + |
| 126 | +`Account`类最终由赋值来实例化。 |
| 127 | + |
| 128 | +```py |
| 129 | +>>> Account = make_account_class() |
| 130 | +``` |
| 131 | + |
| 132 | +之后,账户实例通过`new`消息来创建,它需要名称来处理新创建的账户。 |
| 133 | + |
| 134 | +```py |
| 135 | +>>> jim_acct = Account['new']('Jim') |
| 136 | +``` |
| 137 | + |
| 138 | +之后,`get`消息传递给`jim_acct `,来获取属性和方法。方法可以调用来更新账户余额。 |
| 139 | + |
| 140 | +```py |
| 141 | +>>> jim_acct['get']('holder') |
| 142 | +'Jim' |
| 143 | +>>> jim_acct['get']('interest') |
| 144 | +0.02 |
| 145 | +>>> jim_acct['get']('deposit')(20) |
| 146 | +20 |
| 147 | +>>> jim_acct['get']('withdraw')(5) |
| 148 | +15 |
| 149 | +``` |
| 150 | + |
| 151 | +就像使用 Python 对象系统那样,设置实例的属性并不会修改类的对应属性: |
| 152 | + |
| 153 | +```py |
| 154 | +>>> jim_acct['set']('interest', 0.04) |
| 155 | +>>> Account['get']('interest') |
| 156 | +0.02 |
| 157 | +``` |
| 158 | + |
| 159 | +**继承。**我们可以创建`CheckingAccount`子类,通过覆盖类属性的子集。在这里,我们修改`withdraw`方法来收取费用,并且降低了利率。 |
| 160 | + |
| 161 | +```py |
| 162 | +>>> def make_checking_account_class(): |
| 163 | + """Return the CheckingAccount class, which imposes a $1 withdrawal fee.""" |
| 164 | + def withdraw(self, amount): |
| 165 | + return Account['get']('withdraw')(self, amount + 1) |
| 166 | + return make_class({'withdraw': withdraw, 'interest': 0.01}, Account) |
| 167 | +``` |
| 168 | + |
| 169 | +在这个实现中,我们在子类的`withdraw `中调用了基类`Account`的`withdraw`函数,就像在 Python 内建对象系统那样。我们可以创建子类本身和它的实例,就像之前那样: |
| 170 | + |
| 171 | +```py |
| 172 | +>>> CheckingAccount = make_checking_account_class() |
| 173 | +>>> jack_acct = CheckingAccount['new']('Jack') |
| 174 | +``` |
| 175 | + |
| 176 | +它们的行为相似,构造函数也一样。每笔取款都会在特殊的`withdraw`函数中收费 $1,并且`interest`也拥有新的较低值。 |
| 177 | + |
| 178 | +```py |
| 179 | +>>> jack_acct['get']('interest') |
| 180 | +0.01 |
| 181 | +>>> jack_acct['get']('deposit')(20) |
| 182 | +20 |
| 183 | +>>> jack_acct['get']('withdraw')(5) |
| 184 | +14 |
| 185 | +``` |
| 186 | + |
| 187 | +我们的构建在字典上的对象系统十分类似于 Python 内建对象系统的实现。Python 中,任何用户定义类的实例,都有个特殊的`__dict__`属性,将对象的局部实例属性储存在字典中,就像我们的`attributes`字典那样。Python 的区别在于,它区分特定的特殊方法,这些方法和内建函数交互来确保那些函数能正常处理许多不同类型的参数。操作不同类型参数的函数是下一节的主题。 |
0 commit comments