|
| 1 | +6.9 如无必要,勿增实体噢 |
| 2 | +======================== |
| 3 | + |
| 4 | +|image0| |
| 5 | + |
| 6 | +删除没必要的调用\ ``keys()`` |
| 7 | +---------------------------- |
| 8 | + |
| 9 | +字典是由一个个的键值对组成的,如果你遍历字典时只需要访问键,用不到值,有很多同学会用下面这种方式: |
| 10 | + |
| 11 | +.. code:: python |
| 12 | +
|
| 13 | + for currency in currencies.keys(): |
| 14 | + process(currency) |
| 15 | +
|
| 16 | +在这种情况下,不需要调用keys(),因为遍历字典时的默认行为是遍历键。 |
| 17 | + |
| 18 | +.. code:: python |
| 19 | +
|
| 20 | + for currency in currencies: |
| 21 | + process(currency) |
| 22 | +
|
| 23 | +现在,该代码更加简洁,易于阅读,并且避免调用函数会带来性能改进。 |
| 24 | + |
| 25 | +简化序列比较 |
| 26 | +------------ |
| 27 | + |
| 28 | +我们经常要做的是在尝试对列表或序列进行操作之前检查列表或序列是否包含元素。 |
| 29 | + |
| 30 | +.. code:: python |
| 31 | +
|
| 32 | + if len(list_of_hats) > 0: |
| 33 | + hat_to_wear = choose_hat(list_of_hats) |
| 34 | +
|
| 35 | +使用Python的方法则更加简单:如果Python列表和序列具有元素,则返回为True,否则为False: |
| 36 | + |
| 37 | +.. code:: python |
| 38 | +
|
| 39 | + if list_of_hats: |
| 40 | + hat_to_wear = choose_hat(list_of_hats) |
| 41 | +
|
| 42 | +仅使用一次的内联变量 |
| 43 | +-------------------- |
| 44 | + |
| 45 | +我们在很多代码中经常看到,有些同学分配结果给变量,然后马上返回它,例如, |
| 46 | + |
| 47 | +.. code:: python |
| 48 | +
|
| 49 | + def state_attributes(self): |
| 50 | + """Return the state attributes.""" |
| 51 | + state_attr = { |
| 52 | + ATTR_CODE_FORMAT: self.code_format, |
| 53 | + ATTR_CHANGED_BY: self.changed_by, |
| 54 | + } |
| 55 | + return state_attr |
| 56 | +
|
| 57 | +如果直接返回,则更加直观、简洁, |
| 58 | + |
| 59 | +.. code:: python |
| 60 | +
|
| 61 | + def state_attributes(self): |
| 62 | + """Return the state attributes.""" |
| 63 | + return { |
| 64 | + ATTR_CODE_FORMAT: self.code_format, |
| 65 | + ATTR_CHANGED_BY: self.changed_by, |
| 66 | + } |
| 67 | +
|
| 68 | +这样可以缩短代码并删除不必要的变量,从而减轻了读取函数的负担。 |
| 69 | + |
| 70 | +|image1| |
| 71 | + |
| 72 | +.. |image0| image:: http://image.iswbm.com/20200804124133.png |
| 73 | +.. |image1| image:: http://image.iswbm.com/20200607174235.png |
| 74 | + |
0 commit comments