├── 101.md ├── 102.md ├── 103.md ├── 104.md ├── 105.md ├── 106.md ├── 107.md ├── 108.md ├── 109.md ├── 110.md ├── 111.md ├── 112.md ├── 113.md ├── 114.md ├── 115.md ├── 201.md ├── 202.md ├── 301.md ├── 302.md ├── 303.md ├── 304.md ├── 305.md ├── 306.md ├── 307.md ├── 308.md ├── 309.md ├── 401.md ├── 402.md └── README.md /101.md: -------------------------------------------------------------------------------- 1 | #Python是否有三元条件运算符? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator 4 | 5 | ##问题: 6 | 7 | 如果没有,是否可以使用其他语言结构来模拟一个? 8 | 9 | ##答案 1 10 | 11 | 是的,在2.5版本以后增加了。语法是: 12 | 13 | a if test else b 14 | 15 | 首先对test进行评估,然后根据test的布尔值返回到a或b; 16 | 17 | 如果test评估结果为真,则返回到a,否则就返回到b。 18 | 19 | 例如: 20 | 21 | >>> 'true' if True else 'false' 22 | 'true' 23 | >>> 'true' if False else 'false' 24 | 'false' 25 | 26 | 记住,一些python开发者对此并不赞成: 27 | 28 | - 参数的顺序不同于许多其他的语言(如:C, Ruby, Java等)。当人们不熟悉Python的“奇怪”行为时(他们可能会颠倒顺序),可能会导致错误。 29 | - 有些人觉得它“不便使用”,因为它违背了常规思路:人们习惯先考虑条件,后考虑效果。 30 | - 格式上的原因。 31 | 32 | 如果你在记忆顺序方面有困难(正如许多人似乎都有这个困难),那么请记住,把它大声读出来,你(几乎)是在说,`x = 4 if b > 8 else 9`被大声读作`x will be 4 if b is greater than 8 otherwise 9`(x就等于4,如果b大于8而不是9)。 33 | 34 | ##答案 2 35 | 36 | 模拟Python三元运算符 37 | 38 | 例如: 39 | 40 | a, b, x, y = 1, 2, 'a greather than b', 'b greater than a' 41 | result = (lambda:y, lambda:x)[a > b]() 42 | 43 | 输出: 44 | 45 | 'b greater than a' 46 | 47 | 48 | ------- 49 | 50 | 打赏帐号:qiwsir@126.com(支付宝),qiwsir(微信号) 51 | -------------------------------------------------------------------------------- /102.md: -------------------------------------------------------------------------------- 1 | #如何把两个Python字典用一个表达式合并? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression 4 | 5 | ##问题: 6 | 7 | 我有两个Python字典,想写一个表达式,实现两个字典的合并。用`update()`方法,如果它能够返回合并结果而不是原地修改,就是我想要的。 8 | 9 | >>> x = {'a':1, 'b': 2} 10 | >>> y = {'b':10, 'c': 11} 11 | >>> z = x.update(y) 12 | >>> print z 13 | None 14 | >>> x 15 | {'a': 1, 'b': 10, 'c': 11} 16 | 17 | 我怎样才能让最终合并后的字典是在z中,而不是在x中?(要格外清楚,最后一个成功解决dict.update()的冲突的方法,也是我所寻求的。) 18 | 19 | ##回答: 20 | 21 | 你有两个字典,你想把它们合并成一个新的字典,而又不改变原有字典中的内容: 22 | 23 | x = {'a': 1, 'b': 2} 24 | y = {'b': 3, 'c': 4} 25 | 26 | y是后一个,它的值将取代x的值,因此'b'将在最终的结果中指向3。 27 | 28 | 经典的Python解法是分两步处理: 29 | 30 | z = x.copy() 31 | z.update(y) 32 | 33 | [PEP 448](https://www.python.org/dev/peps/pep-0448)中提出的新语法在 [Python 3.5](https://mail.python.org/pipermail/python-dev/2015-February/138564.html)中可用。新语法是这样的 34 | 35 | z = {**x, **y} 36 | 37 | 它满足了你所提出的要求(单一的表达式)。它符合[Python 3.5 PEP 478](https://www.python.org/dev/peps/pep-0478/#features-for-3-5),并且它已经出现在文档[What's New in Python 3.5](https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations)中。 38 | 39 | 然而,由于许多组织仍然在使用Python 2,在未来几年的时间里,新语法都不太可能在生产环境中被使用。 40 | 41 | ###在Python 2中,合并字典的表达式 42 | 43 | 随着许多组织把Python版本升级到Python 3,Python 3.5中提出的新的解决方案将会成为这个问题的主要解决方案。 44 | 45 | 然而,如果你还没有使用Python 3.5,并且你还想在一个表达式中实现这个功能,最高效的方法就是把它放在一个函数中: 46 | 47 | def merge_two_dicts(x, y): 48 | '''Given two dicts, merge them into a new dict as a shallow copy.''' 49 | z = x.copy() 50 | z.update(y) 51 | return z 52 | 53 | 然后,你就有一个单一的表达式: 54 | 55 | z = merge_two_dicts(x, y) 56 | 57 | 你也可以创建一个函数来合并一些数量不确定的字典,从零到一个非常大的数量: 58 | 59 | def merge_dicts(*dict_args): 60 | ''' 61 | Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. 62 | ''' 63 | result = {} 64 | for dictionary in dict_args: 65 | result.update(dictionary) 66 | return result 67 | 68 | 这个函数对于Python 2和Python 3中所有的字典都适用。例如,在给定的从a到g的字典中, 69 | 70 | z = merge_dicts(a, b, c, d, e, f, g) 71 | 72 | 字典g中的键值对优先于字典a到f,依此类推(即“最后一个有效”——译者注)。 73 | 74 | ###对其他答案的评论 75 | 76 | 不要采用你所看到的投票最多的答案: 77 | 78 | z = dict(x.items() + y.items()) 79 | 80 | 在Python 2中,你在内存中为这两个字典创建两个列表,创建的第三个列表的长度等于前两个列表加起来的长度,然后创建字典并丢弃所有这三个列表。在Python 3中,这样做就行不通了,因为你是把两个dict_items加在一起,而不是两个列表。 81 | 82 | >>> c = dict(a.items() + b.items()) 83 | Traceback (most recent call last): 84 | File "", line 1, in 85 | TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items' 86 | and you would have to explicitly create them as lists, e.g. z = dict(list(x.items()) + list(y.items())). This is a waste of resources and computation power. 87 | 88 | 你必须明确地把它们作为列表来创建,例如`z = dict(list(x.items()) + list(y.items()))`。这是对资源和计算能力的一种浪费。 89 | 90 | 同样地,如果值不是可哈希对象(例如:列表),在Python 3 中合并items()也不会成功(Python 2.7中viewitems())。即使你的值是可哈希的,因为字典是无序的,也没有定义行为的优先顺序。所以不要这样做: 91 | 92 | >>> c = dict(a.items() | b.items()) 93 | 94 | 这个例子说明了如果值不是哈希表时会发生什么情况: 95 | 96 | >>> x = {'a': []} 97 | >>> y = {'b': []} 98 | >>> dict(x.items() | y.items()) 99 | Traceback (most recent call last): 100 | File "", line 1, in 101 | TypeError: unhashable type: 'list' 102 | 103 | 这里有一个例子,它说明了y在什么情况下应该有优先权,但是由于字典的顺序是任意的,x的值被保留下来: 104 | 105 | >>> x = {'a': 2} 106 | >>> y = {'a': 1} 107 | >>> dict(x.items() | y.items()) 108 | {'a': 2} 109 | 110 | 你不应该使用的另一个把戏: 111 | 112 | z = dict(x, **y) 113 | 114 | 这里使用了字典构造器,并且速度非常快、内存效率高(甚至略高于我们的两步法)。但是这个把戏很难读懂,除非你确切地知道这里发生了什么情况(第二个字典被作为关键字参数传递给字典构造器),这不是预期的用法,所以不Python。另外,当关键字不是字符串时,这种方法在Python 3中也行不通。 115 | 116 | >>> c = dict(a, **b) 117 | Traceback (most recent call last): 118 | File "", line 1, in 119 | TypeError: keyword arguments must be strings 120 | 121 | 在[邮件列表](https://mail.python.org/pipermail/python-dev/2010-April/099459.html)中,吉多·范罗苏姆,Python语言的创造者,写到: 122 | 123 | >“I am fine with declaring `dict({}, **{1:3})` illegal, since after all it is abuse of the `**` mechanism.” 124 | >“我可以宣布`dict({}, **{1:3})`是非法的,因为这毕竟是在滥用`**`机制。” 125 | 126 | >“Apparently dict(x, **y) is going around as "cool hack" for "call x.update(y) and return x". Personally I find it more despicable than cool.” 127 | >“显然,`dict(x, **y)`是对于`x.update(y) and return x`的“酷黑”。我个人觉得它不是‘酷’而是卑劣。” 128 | 129 | ###正确但性能不高的点对点模式 130 | 131 | 这些方法的性能不高,但它们将提供正确的功能,性能会比copy和update或新的unpacking低得多,因为它们在更高的抽象层次上遍历每个键值对,但它们肯定尊重优先顺序(后面的字典优先) 132 | 133 | 你也可以在字典的解析式中创建字典: 134 | 135 | {k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7 136 | 137 | 或者在Python 2.6中(也许早在引入了生成器表达式的Python2.4中): 138 | 139 | dict((k, v) for d in dicts for k, v in d.items()) 140 | 141 | itertools.chain将迭代器的键值对按正确的顺序链接起来: 142 | 143 | import itertools 144 | z = dict(itertools.chain(x.iteritems(), y.iteritems())) 145 | 146 | ###性能分析 147 | 148 | 我只对能够正确运行的那些用法进行性能分析。 149 | 150 | import timeit 151 | 152 | 以下适用于Ubuntu 14.04和Python 2.7(Python系统): 153 | 154 | >>> min(timeit.repeat(lambda: merge_two_dicts(x, y))) 155 | 0.5726828575134277 156 | >>> min(timeit.repeat(lambda: {k: v for d in (x, y) for k, v in d.items()} )) 157 | 1.163769006729126 158 | >>> min(timeit.repeat(lambda: dict(itertools.chain(x.iteritems(), y.iteritems())))) 159 | 1.1614501476287842 160 | >>> min(timeit.repeat(lambda: dict((k, v) for d in (x, y) for k, v in d.items()))) 161 | 2.2345519065856934 162 | 163 | Python 3.5: 164 | 165 | >>> min(timeit.repeat(lambda: {**x, **y})) 166 | 0.4094954460160807 167 | >>> min(timeit.repeat(lambda: merge_two_dicts(x, y))) 168 | 0.7881555100320838 169 | >>> min(timeit.repeat(lambda: {k: v for d in (x, y) for k, v in d.items()} )) 170 | 1.4525277839857154 171 | >>> min(timeit.repeat(lambda: dict(itertools.chain(x.items(), y.items())))) 172 | 2.3143140770262107 173 | >>> min(timeit.repeat(lambda: dict((k, v) for d in (x, y) for k, v in d.items()))) 174 | 3.2069112799945287 175 | 176 | 177 | ------- 178 | 179 | 打赏帐号:qiwsir@126.com(支付宝) 180 | -------------------------------------------------------------------------------- /103.md: -------------------------------------------------------------------------------- 1 | #对Python字典按值排序 2 | 3 | 原问题地址:http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value 4 | 5 | ##问题: 6 | 7 | 我有一个值的字典,它的值来自于数据库中的两个字段:字符串字段和数字字段。字符串字段是独一无二的,字典的键也是如此。 8 | 9 | 我可以按键排序,但我怎么才能按值排序? 10 | 11 | 注:我读了Stack Overflow的问题:[我如何在Python中对字典列表按值排序?](http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python),我也许能够改变我的代码来获取字典列表,但我真的不需要字典列表,我想知道是否有一个更简单的解决方案。 12 | 13 | ##答案 1: 14 | 15 | 对一个字典排序,却只得到这个经过排序的字典,这是不可能的。字典本质上是无序的,但其他类型,如列表和元组,却是有序的。所以你需要一个排序表示法,也就是一个列表,很可能是元组的列表。 16 | 17 | 例如, 18 | 19 | import operator 20 | x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} 21 | sorted_x = sorted(x.items(), key=operator.itemgetter(1)) 22 | 23 | sorted_x将会是元组的列表,这个列表根据每个元组中的第二个元素来排序。dict(sorted_x) == x。 24 | 25 | 如果你希望根据键而不是根据值进行排序: 26 | 27 | import operator 28 | x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} 29 | sorted_x = sorted(x.items(), key=operator.itemgetter(0)) 30 | 31 | ##答案 2: 32 | 33 | 你可以使用: 34 | 35 | sorted(d.items(), key=lambda x: x[1]) 36 | 37 | 这是按照字典中每个条目的值从小到大的顺序进行排序。 38 | 39 | ##答案 3: 40 | 41 | 字典不可以排序,但是你可以为它们建立一个有序的列表。 42 | 43 | 按照字典的值排序后的列表: 44 | 45 | sorted(d.values()) 46 | 47 | 按值排序的(键、值)对的列表: 48 | 49 | from operator import itemgetter 50 | sorted(d.items(), key=itemgetter(1)) 51 | -------------------------------------------------------------------------------- /104.md: -------------------------------------------------------------------------------- 1 | #append和extend的区别 2 | 3 | 原问题地址:http://stackoverflow.com/questions/252703/python-append-vs-extend 4 | 5 | ##问题 6 | 7 | 列表的两个方法`append()`和`extend()`的区别是什么? 8 | 9 | ##答案: 10 | 11 | [append](https://docs.python.org/2/library/array.html?#array.array.append):在末尾添加对象 12 | 13 | x = [1, 2, 3] 14 | x.append([4, 5]) 15 | print (x) 16 | 17 | 得出:`[1, 2, 3, [4, 5]]` 18 | 19 | [extend](https://docs.python.org/2/library/array.html?#array.array.extend):通过添加可迭代对象的元素来扩展列表 20 | 21 | x = [1, 2, 3] 22 | x.extend([4, 5]) 23 | print (x) 24 | 25 | 得出: `[1, 2, 3, 4, 5]` 26 | -------------------------------------------------------------------------------- /105.md: -------------------------------------------------------------------------------- 1 | #获得Python的循环索引 2 | 3 | 原问题地址:http://stackoverflow.com/questions/522563/accessing-the-index-in-python-for-loops 4 | 5 | ##问题: 6 | 7 | 是否有人知道如何得到列表自身的索引,比如: 8 | 9 | ints = [8, 23, 45, 12, 78] 10 | 11 | 当我使用for循环这个列表的时候,如何得到从1到5的索引? 12 | 13 | ##答案: 14 | 15 | 使用额外的状态变量,如索引变量(你在C语言或PHP语言中通常会用到它),这被认为不是Python的风格。 16 | 17 | 更好的选择是使用Python 2和Python 3中的内建函数`[enumerate()](https://docs.python.org/2/library/functions.html#enumerate)`: 18 | 19 | for idx, val in enumerate(ints): 20 | print idx, val 21 | 22 | 更多信息请查看[PEP 279](https://www.python.org/dev/peps/pep-0279/)。 23 | -------------------------------------------------------------------------------- /106.md: -------------------------------------------------------------------------------- 1 | #判断一个字符串是否含子串的方法 2 | 3 | 原问题地址:http://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method 4 | 5 | ##问题: 6 | 7 | 我在Python中查找`string.contains`或`string.indexof`方法。 8 | 9 | 我想实现: 10 | 11 | if not somestring.contains("blah"): 12 | continue 13 | 14 | ##回答 1: 15 | 16 | 你可以使用[in](https://docs.python.org/reference/expressions.html#membership-test-details): 17 | 18 | if "blah" not in somestring: 19 | continue 20 | 21 | ##回答 2: 22 | 23 | 如果你只是搜索一个子字符串,可以使用`string.find("substring")`。 24 | 25 | 然而,你使用`find`,`index` 和 `in`的时候一定要小心一点,因为这是在搜索子字符串。换句话说,下面的内容: 26 | 27 | s = "This be a string" 28 | if s.find("is") == -1: 29 | print "No 'is' here!" 30 | else: 31 | print "Found 'is' in the string." 32 | 33 | 打印结果是:`Found 'is' in the string`。类似于`if "is" in s:`。 34 | 35 | 这可能是你想要的,也可能不是。 36 | 37 | -------------------------------------------------------------------------------- /107.md: -------------------------------------------------------------------------------- 1 | #怎样在Python中实现Enum(枚举)的功能 2 | 3 | 原问题地址:http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python 4 | 5 | ##问题: 6 | 7 | 我是一个C#开发者,但目前致力于Python的一个项目。 8 | 9 | 我怎样在Python中实现类似于Enum(枚举)的功能? 10 | 11 | ##回答: 12 | 13 | 根据 [PEP 435](http://www.python.org/dev/peps/pep-0435/)中的描述,Enums已被添加到Python 3.4 中。在[Python3.3,3.2,3.1,2.7,2.6,2.5和2.4的pypi中也增添了Enums](https://pypi.python.org/pypi/enum34)。 14 | 15 | 对于更高级的Enum技术,请访问[aenum library](https://pypi.python.org/pypi/aenum)(Python 2.7,3.3+,和enum34是同一作者)。 16 | 17 | - 使用enum34,安装方法`$ pip install enum34` 18 | - 使用aenum, 安装方法 `$ pip install aenum` 19 | 20 | 安装enum(无编号)将得到一个完全不同的、不兼容的版本。 21 | 22 | from enum import Enum # for enum34, or the stdlib version 23 | # from aenum import Enum # for the aenum version 24 | Animal = Enum('Animal', 'ant bee cat dog') 25 | 26 | 或者相当于: 27 | 28 | class Animal(Enum): 29 | ant = 1 30 | bee = 2 31 | cat = 3 32 | dog = 4 33 | 34 | 在早期版本中,实现enums的一种方法是: 35 | 36 | def enum(**enums): 37 | return type('Enum', (), enums) 38 | 39 | 它是这样运行的: 40 | 41 | >>> Numbers = enum(ONE=1, TWO=2, THREE='three') 42 | >>> Numbers.ONE 43 | 1 44 | >>> Numbers.TWO 45 | 2 46 | >>> Numbers.THREE 47 | 'three' 48 | 49 | 你还可以用这样的代码很容易地支持自动枚举: 50 | 51 | def enum(*sequential, **named): 52 | enums = dict(zip(sequential, range(len(sequential))), **named) 53 | return type('Enum', (), enums) 54 | 55 | 它是这样运行的: 56 | 57 | >>> Numbers = enum('ZERO', 'ONE', 'TWO') 58 | >>> Numbers.ZERO 59 | 0 60 | >>> Numbers.ONE 61 | 1 62 | 63 | 你可以用这种方法把值转换为名称: 64 | 65 | def enum(*sequential, **named): 66 | enums = dict(zip(sequential, range(len(sequential))), **named) 67 | reverse = dict((value, key) for key, value in enums.iteritems()) 68 | enums['reverse_mapping'] = reverse 69 | return type('Enum', (), enums) 70 | 71 | 这样做将覆盖任何带有该名字的内容,但是它有助于在输出时渲染你的enums(枚举)。如果反向映射不存在,它将放弃KeyError。下面看第一个例子: 72 | 73 | >>> Numbers.reverse_mapping['three'] 74 | 'THREE' -------------------------------------------------------------------------------- /108.md: -------------------------------------------------------------------------------- 1 | #将多行的异常变成一行 2 | 3 | 原问题地址:http://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block 4 | 5 | ##问题: 6 | 7 | 我知道我可以这样做: 8 | 9 | try: 10 | # do something that may fail 11 | except: 12 | # do this if ANYTHING goes wrong 13 | 14 | 我也可以这样做: 15 | 16 | try: 17 | # do something that may fail 18 | except IDontLikeYourFaceException: 19 | # put on makeup or smile 20 | except YouAreTooShortException: 21 | # stand on a ladder 22 | 23 | 但是,如果我想在两种异常中实现同样的功能,我现在可以想出的最好的办法是这样的: 24 | 25 | try: 26 | # do something that may fail 27 | except IDontLIkeYouException: 28 | # say please 29 | except YouAreBeingMeanException: 30 | # say please 31 | 32 | 有没有什么办法让我可以实现下面的功能(因为在这两种异常中都要做`say please`): 33 | 34 | try: 35 | # do something that may fail 36 | except IDontLIkeYouException, YouAreBeingMeanException: 37 | # say please 38 | 39 | 现在这样做行不通,因为它和下面代码的语法相匹配: 40 | 41 | try: 42 | # do something that may fail 43 | except Exception, e: 44 | # say please 45 | 46 | 47 | 所以,我为了捕捉到这两种不同的异常所做的努力并没有奏效。 48 | 49 | 有办法成功做到吗? 50 | 51 | ##回答: 52 | 53 | 用圆括号括起来 54 | 55 | except (IDontLIkeYouException, YouAreBeingMeanException) as e: 56 | pass 57 | 58 | 在Python 2.6和Python2.7中仍然可以用逗号把异常分开,但现在这样做已经过时了,不再适用于现在所使用的Python 3。现在你应该使用`as`。 59 | -------------------------------------------------------------------------------- /109.md: -------------------------------------------------------------------------------- 1 | #解释Python的切片法 2 | 3 | 原问题地址: 4 | http://stackoverflow.com/questions/509211/explain-pythons-slice-notation 5 | 6 | ##问题: 7 | 8 | 我需要关于Python切片明确说明(包括参考文献)。 9 | 10 | 对我来说,切片问题有点费神。它看起来非常强大,但我还没有完全搞清楚。 11 | 12 | ##回答: 13 | 14 | Python切片很简单: 15 | 16 | a[start:end] # items start through end-1 17 | a[start:] # items start through the rest of the array 18 | a[:end] # items from the beginning through end-1 19 | a[:] # a copy of the whole array 20 | 21 | 还有步长,它可以用在上面任何一处中: 22 | 23 | a[start:end:step] # start through not past end, by step 24 | 25 | 要记住的关键点是:`:end`中的`end`所表示的值表示所选定的切片之后的第一值【译者注:也就是`end`的值所对应的字符,没有包括在所选定的切片之中。可以概括为“前包括,后不包括”的范围选择原则。】所以,结束和起始的区别是索引是否被乃入切片范围(如果步长是默认值1)。 26 | 27 | 另一个特点是,起始或结束可能是负数,这就意味着它是从数组的末尾开始计数,而不是起始处开始计数。所以: 28 | 29 | a[-1] # last item in the array 30 | a[-2:] # last two items in the array 31 | a[:-2] # everything except the last two items 32 | 33 | 如果实际元素少于所提交的元素个数,Python会给出温和的反馈。例如,如果你执行`a[:-2]`,而`a`只包含一个元素,反馈给你的就是空的列表,而不是错误列表。有时候,你更愿意得到错误提示,所以你一定要知道出现这种情况的可能性。 34 | -------------------------------------------------------------------------------- /110.md: -------------------------------------------------------------------------------- 1 | #如何在Python中获取当前时间 2 | 3 | 原问题地址:http://stackoverflow.com/questions/415511/how-to-get-current-time-in-python 4 | 5 | ##问题: 6 | 7 | 获取当前时间所用的模块/方法是什么? 8 | 9 | ##回答: 10 | 11 | >>> import datetime 12 | >>> datetime.datetime.now() 13 | datetime(2009, 1, 6, 15, 8, 24, 78915) 14 | 15 | 仅是时间: 16 | 17 | >>> datetime.datetime.time(datetime.datetime.now()) 18 | datetime.time(15, 8, 24, 78915) 19 | 20 | 另一种: 21 | 22 | >>> datetime.datetime.now().time() 23 | 24 | 阅读此[文档](https://docs.python.org/2/library/datetime.html)获取更多信息。 25 | 26 | 为了免去打字的麻烦,你可以从datetime模块引入datetime对象: 27 | 28 | >>> from datetime import datetime 29 | 30 | 然后删除前面所有前置的datetime。 31 | -------------------------------------------------------------------------------- /111.md: -------------------------------------------------------------------------------- 1 | #查看某个给定的键是否已经在字典中 2 | 3 | 原问题地址:http://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary 4 | 5 | ##问题: 6 | 7 | 更新某键的值以前,我想先知道它是否存在于字典中。我写了以下代码: 8 | 9 | if 'key1' in dict.keys(): 10 | print "blah" 11 | else: 12 | print "boo" 13 | 14 | 我认为这不是完成此任务的最佳方法。有没有更好的方法来知晓字典中的某个键? 15 | 16 | ##回答: 17 | 18 | `in`就是用于探知字典中是否存在某个键的一种方式 19 | 20 | d = dict() 21 | 22 | for i in xrange(100): 23 | key = i % 10 24 | if key in d: 25 | d[key] += 1 26 | else: 27 | d[key] = 1 28 | 29 | 如果你想要一个默认值,可以使用`dict.get()`: 30 | 31 | d = dict() 32 | 33 | for i in xrange(100): 34 | key = i % 10 35 | d[key] = d.get(key, 0) + 1 36 | 37 | 如果你想一直确保某个键的默认值,可以使用collections模块中的defaultdict,就像下面这样: 38 | 39 | from collections import defaultdict 40 | 41 | d = defaultdict(lambda: 0) 42 | 43 | for i in xrange(100): 44 | d[i % 10] += 1 45 | 46 | 但一般说来,关键字in是用于探知字典中是否存在某个键的最佳方法。 47 | -------------------------------------------------------------------------------- /112.md: -------------------------------------------------------------------------------- 1 | #如何删除Python中的换行符? 2 | 3 | 原问题地址: 4 | http://stackoverflow.com/questions/275018/how-can-i-remove-chomp-a-newline-in-python 5 | 6 | ##问题: 7 | 8 | 在Python中,什么是与Perl 的`chomp` 功能相对应,用于消除某个值的最后一个字符? 9 | 10 | 回答: 11 | 12 | 尝试`rstrip`方法。 13 | 14 | >>> 'test string\n'.rstrip() 15 | 'test string' 16 | 17 | 注意Python中的rstrip方法是以默认的方式除去各种尾部空格,而不只是像Perl中的chomp那样除去换行符。为了达到只除去换行符的目的: 18 | 19 | >>> 'test string \n'.rstrip('\n') 20 | 'test string ' 21 | 22 | 你还可以使用lstrip和strip方法。 23 | 24 | >>> s = " \n abc def " 25 | >>> s.strip() 26 | 'abc def' 27 | >>> s.rstrip() 28 | ' \n abc def' 29 | >>> s.lstrip() 30 | 'abc def ' 31 | >>> -------------------------------------------------------------------------------- /113.md: -------------------------------------------------------------------------------- 1 | #如何将Python列表均匀划分? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python 4 | 5 | ##问题: 6 | 7 | 我有一个任意长度的列表,我需要把它拆分成长度相等的更小的数据集,然后进行操作。有一些平淡无奇的方法可以实现这一需求,比如:保存一个计数器和两个列表,当第二个列表填满时,将第二个列表添加到第一个列表,然后清空第二个列表以便填充下一轮数据,但这样做的代价可能是非常昂贵的。 8 | 9 | 我想知道是否有人想出了一个很好的解决方案,使之适用于于任何长度的列表,例如;使用生成器。 10 | 11 | 这个方案应该能够奏效: 12 | 13 | l = range(1, 1000) 14 | print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] 15 | 16 | 我曾经在itertools中寻找一些有用的东西,但我找不到任何明显有用的东西。然而,我可能错过了它。 17 | 18 | ##回答: 19 | 20 | 这是一个生成器,它可以生成你想要的数据集: 21 | 22 | def chunks(l, n): 23 | """Yield successive n-sized chunks from l.""" 24 | for i in range(0, len(l), n): 25 | yield l[i:i+n] 26 | 27 | import pprint 28 | pprint.pprint(list(chunks(range(10, 75), 10))) 29 | [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], 30 | [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], 31 | [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], 32 | [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], 33 | [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], 34 | [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], 35 | [70, 71, 72, 73, 74]] 36 | 37 | 如果你正在使用Python 2,你应该使用`xrange()`来代替`range()`: 38 | 39 | def chunks(l, n): 40 | """Yield successive n-sized chunks from l.""" 41 | for i in xrange(0, len(l), n): 42 | yield l[i:i+n] 43 | 44 | 你也可以简单地使用列表解析来代替函数的书写。 45 | 46 | Python 3: 47 | 48 | [l[i:i+n] for i in range(0, len(l), n)] 49 | 50 | Python2: 51 | 52 | [l[i:i+n] for i in xrange(0, len(l), n)] 53 | -------------------------------------------------------------------------------- /114.md: -------------------------------------------------------------------------------- 1 | #Python中的join函数为什么是string.join(list)而不是list.join(string)? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/493819/python-join-why-is-it-string-joinlist-instead-of-list-joinstring 4 | 5 | ##问题: 6 | 7 | 这个问题一直困扰着我。这样的书写看起来 8 | 9 | my_list = ["Hello", "world"] 10 | print my_list.join("-") 11 | # Produce: "Hello-world" 12 | 13 | 胜过这样的书写: 14 | 15 | my_list = ["Hello", "world"] 16 | print "-".join(my_list) 17 | # Produce: "Hello-world" 18 | 19 | 这里面是否有个特殊的原因呢? 20 | 21 | ##回答: 22 | 23 | 这是因为可以被加进来的不只是列表,还可以是任何一个可迭代对象,但结果和连接符始终都是字符串。 24 | 25 | 例如: 26 | 27 | import urllib2 28 | print '\n############\n'.join( 29 | urllib2.urlopen('http://data.stackexchange.com/users/7095')) 30 | -------------------------------------------------------------------------------- /115.md: -------------------------------------------------------------------------------- 1 | #我如何在Python中检查一个字符串否可转化为数字? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python 4 | 5 | ##问题: 6 | 7 | 在Python中,检查一个字符串是否可以表示为数字的最可行的办法是什么? 8 | 9 | 我现在所使用的函数是: 10 | 11 | def is_number(s): 12 | try: 13 | float(s) 14 | return True 15 | except ValueError: 16 | return False 17 | 18 | 这个函数不仅丑陋、缓慢,似乎还很笨拙。但是我还没有找到一个更好的方法,在应用中直接使用float()更差劲了。 19 | 20 | ##回答: 21 | 22 | 我只谈两点。 23 | 24 | 一个正则表达式或其他字符串解析将会更加丑陋和缓慢。 25 | 26 | 我不知道有什么函数比上面的函数更快。它调用函数并返回。Try/Catch不会招致太多代价,因为我们所遇到的最常见的例外也无需扩展搜索堆栈帧。 27 | 28 | 问题是任何数字转换函数都有两种结果 29 | 30 | - 数字,如果这个数字是有效的 31 | - 代码状态(例如,通过errno)或异常,显示没有有效的数字可以解析。 32 | 33 | C语言(举个例子)围绕这个问题提出了许多方法。Python提供了清晰、明确的表达。 34 | 35 | 我认为你的代码完美地解决了这个问题。 36 | -------------------------------------------------------------------------------- /201.md: -------------------------------------------------------------------------------- 1 | #如何使用Python来检查文件是否存在? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/82831/how-to-check-whether-a-file-exists-using-python 4 | 5 | ##问题: 6 | 7 | 我如何使用Python而不使用`try-catch`语句来检查文件是否存在? 8 | 9 | ##答案 1 10 | 11 | 你也可以使用`os.path.isfile` 12 | 13 | 如果是一个现有的常规文件,就返回到True。这是符号链接,所以`islink()`和`isfile()`可以适用于相同的路径。 14 | 15 | import os.path 16 | os.path.isfile(fname) 17 | 18 | 如果你需要确保它是一个文件。 19 | 20 | ##答案 2: 21 | 22 | 用`os.path.exists`: 23 | 24 | import os.path 25 | os.path.exists(file_path) 26 | 27 | 如果是文件和目录,都会返回到True。但是你还可以使用`os.path.isfile`来专门查看它是否是一个文件。 28 | 29 | ------- 30 | 31 | 打赏帐号:qiwsir@126.com(支付宝),qiwsir(微信号) 32 | -------------------------------------------------------------------------------- /202.md: -------------------------------------------------------------------------------- 1 | #如何在Python中列出目录下的所有文件 2 | 3 | 原问题地址:http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python 4 | 5 | ##问题: 6 | 7 | 我如何在Python中列出目录下的所有文件并将它们添加到一个列表? 8 | 9 | ##回答: 10 | 11 | 使用[os.listdir()](https://docs.python.org/2/library/os.html#os.listdir)可以获取目录中的所有内容 —— 文件和子目录。 12 | 13 | 如果你只想获取文件,你可以使用`os.path`进行过滤 14 | 15 | from os import listdir 16 | from os.path import isfile, join 17 | onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] 18 | 19 | 或者可以使用[os.walk()](https://docs.python.org/2/library/os.html#os.walk)。你所访问的每个目录都将生成两个列表 —— 文件列表和目录列表。如果你想要的只是顶层目录,你可以在目录列表第一次生成的时候就结束它。 20 | 21 | from os import walk 22 | 23 | f = [] 24 | for (dirpath, dirnames, filenames) in walk(mypath): 25 | f.extend(filenames) 26 | break 27 | 28 | 最后,正如上面这个例子所表明的那样,要把一个列表添加到另一个列表,你可以使用[.extend()](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)或 29 | 30 | >>> q = [1, 2, 3] 31 | >>> w = [4, 5, 6] 32 | >>> q = q + w 33 | >>> q 34 | [1, 2, 3, 4, 5, 6] 35 | 36 | 就我个人而言,我更喜欢`.extend()` 37 | -------------------------------------------------------------------------------- /301.md: -------------------------------------------------------------------------------- 1 | #Python中yield关键词的作用是什么? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python 4 | 5 | ##问题: 6 | 7 | 在Python中yield关键字的作用是什么?它是做什么用的? 8 | 9 | 例如,我正试图理解这段代码: 10 | 11 | def node._get_child_candidates(self, distance, min_dist, max_dist): 12 | if self._leftchild and distance - max_dist < self._median: 13 | yield self._leftchild 14 | if self._rightchild and distance + max_dist >= self._median: 15 | yield self._rightchild 16 | 17 | 这是调用代码: 18 | 19 | result, candidates = list(), [self] 20 | while candidates: 21 | node = candidates.pop() 22 | distance = node._get_dist(obj) 23 | if distance <= max_dist and distance >= min_dist: 24 | result.extend(node._values) 25 | candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) 26 | return result 27 | 28 | 当调用`_get_child_candidates`方法的时候发生了什么呢?返回某一个列表?返回某一个元素?它是不是再次被调用了?后续调用什么时候才会停下来? 29 | 30 | 注:这里的代码是Jochen Schulz(jrschulz)写的。他建立了一个很棒的度量空间的Python库。点击这个链接就可以看到完整的源代码:[Module mspace](http://well-adjusted.de/~jrschulz/mspace/)。 31 | 32 | ##答案 1: 33 | 34 | 要了解yield是做什么用的,你就必须了解什么是生成器。在了解生成器之前,先要了解可迭代。 35 | 36 | ###可迭代 37 | 38 | 当你创建一个列表后,可以逐个读取它的元素。对一个列表的逐个读取被称为迭代。 39 | 40 | >>> for i in mylist: 41 | ... print(i) 42 | 1 43 | 2 44 | 3 45 | 46 | mylist就是可迭代的。当使用列表解析时,你就创建了一个列表,也就是一个可迭代对象: 47 | 48 | >>> mylist = [x*x for x in range(3)] 49 | >>> for i in mylist: 50 | ... print(i) 51 | 0 52 | 1 53 | 4 54 | 55 | 所有可以使用"for... in..."的对象都是可迭代的,如:列表, 字符串, 文件… 56 | 57 | 这些可迭代对象使用起来很方便,因为你可以随心所欲。但是所有的值都存在了内存中,当有大量数据的时候,这就不是你想要的结果了。 58 | 59 | ###生成器 60 | 61 | 生成器是迭代器,但只能遍历一次。这是因为并非所有的值都在内存中,它们被实时生成: 62 | 63 | >>> mygenerator = (x*x for x in range(3)) 64 | >>> for i in mygenerator: 65 | ... print(i) 66 | 0 67 | 1 68 | 4 69 | 70 | 除非你用`()`来代替`[]`,否则上面两段代码的效果是一样的。但是,你不能再次运行`for i in mygenerator`,因为生成器只能使用一次:他们计算0,然后忘掉它(不保存)并计算1,最后计算4,一个接一个地进行。 71 | 72 | ###Yield 73 | 74 | Yield是一个关键词,它的用法就像return,只不过它返回一个生成器。 75 | 76 | >>> def createGenerator(): 77 | ... mylist = range(3) 78 | ... for i in mylist: 79 | ... yield i*i 80 | ... 81 | >>> mygenerator = createGenerator() # create a generator 82 | >>> print(mygenerator) # mygenerator is an object! 83 | 84 | >>> for i in mygenerator: 85 | ... print(i) 86 | 0 87 | 1 88 | 4 89 | 90 | 这段代码示例没什么用处,但是当你知道函数要返回大量的并且仅需要读一次的数据时,就会觉得它是方便的。 91 | 92 | 要掌握yield,你就必须明白,当你调用这个函数时,写在函数体里的代码并没有运行。该函数只返回到生成器对象,这可有点棘手。 93 | 94 | 接下来,每当for使用生成器的时候,你的代码就会被运行。 95 | 96 | 现在的困难部分是: 97 | 98 | 第一次用for调用你的函数所创建的生成器对象时,它将会从头开始运行函数中的代码,直到遇到yield,才会返回该循环中的第一个值。然后,每次调用都会再运行一次函数中你所写的循环,并返回下一个值,直到没有什么值可以返回。 99 | 100 | 一旦函数在运行过程中不再遇到yield,生成器就会被认为是空的。这可能是因为循环已经结束,或者因为你不再满足"if/else"条件了。 101 | 102 | ###代码说明 103 | 104 | 生成器: 105 | 106 | #这里是你创建node对象的方法,它将返回生成器 107 | def node._get_child_candidates(self, distance, min_dist, max_dist): 108 | 109 | #这里是你每次使用生成器对象时所调用的代码: 110 | #如果它的左边仍有一个节点对象的子节点 111 | #如果距离尚可,返回下一个子节点 112 | if self._leftchild and distance - max_dist < self._median: 113 | yield self._leftchild 114 | 115 | #如果它的右边仍有一个节点对象的子节点 116 | #如果距离尚可,返回下一个子节点 117 | 118 | if self._rightchild and distance + max_dist >= self._median: 119 | yield self._rightchild 120 | 121 | #如果函数到达这里,生成器将被视为空 122 | #这里只有两个值:左边的子节点、右边的子节点 123 | 124 | 调用代码: 125 | 126 | #创建一个空的列表和一个具有当前对象引用的列表 127 | result, candidates = list(), [self] 128 | 129 | #候选项的循环(它们一开始只包含一个元素) 130 | while candidates: 131 | 132 | #找到最后的候选项并且从列表中删除它 133 | node = candidates.pop() 134 | 135 | #获取obj(当前对象)和候选项之间的距离 136 | distance = node._get_dist(obj) 137 | 138 | #如果距离尚可,那么你可以填写结果 139 | if distance <= max_dist and distance >= min_dist: 140 | result.extend(node._values) 141 | 142 | #在候选项名单中添加候选项的子项 143 | #这样一来,该循环将继续运行直到 144 | #所有候选项的子项的子项都运行完毕 145 | candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) 146 | 147 | 返回结果 148 | 149 | 此代码包含几个巧妙的部分: 150 | 151 | - 该循环迭代一个列表,但在迭代过程中列表会扩大。这是运行所有的嵌套数据的一个简洁的方法。只不过这样做有点危险,因为你最终可能会遇到死循环。在这个示例中,`candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))`会读取这个生成器的所有的值,但while循环不断创造新的生成器对象,它们会从以前的生成器对象中产生出不同的值,因为所应用的节点不同。 152 | 153 | - 列表的`extend()`方法,允许可迭代对象并把值添加到列表中。 154 | 155 | 通常我们给`extend()`方法传一个列表: 156 | 157 | >>> a = [1, 2] 158 | >>> b = [3, 4] 159 | >>> a.extend(b) 160 | >>> print(a) 161 | [1, 2, 3, 4] 162 | 163 | 但在代码中,会接收生成器,这是好现象,因为: 164 | 165 | 1. 你不需要把这些重复读取。 166 | 167 | 2. 你可以有很多子节点,并且不希望把它们都存在内存中。 168 | 169 | 它之所以奏效是因为Python不在乎一种方法的参数是不是一个列表。Python允许迭代,因此它可以使用字符串、列表、元组和生成器。这就是所谓的鸭子类型,这也是Python很酷的原因之一。但这是另一个故事了,另一个问题… 170 | 171 | 你可以停在这里,或者读一点关于生成器的高级使用方法: 172 | 173 | ###控制生成器的损耗 174 | 175 | >>> class Bank(): # let's create a bank, building ATMs 176 | ... crisis = False 177 | ... def create_atm(self): 178 | ... while not self.crisis: 179 | ... yield "$100" 180 | >>> hsbc = Bank() # when everything's ok the ATM gives you as much as you want 181 | >>> corner_street_atm = hsbc.create_atm() 182 | >>> print(corner_street_atm.next()) 183 | $100 184 | >>> print(corner_street_atm.next()) 185 | $100 186 | >>> print([corner_street_atm.next() for cash in range(5)]) 187 | ['$100', '$100', '$100', '$100', '$100'] 188 | >>> hsbc.crisis = True # crisis is coming, no more money! 189 | >>> print(corner_street_atm.next()) 190 | 191 | >>> wall_street_atm = hsbc.create_atm() # it's even true for new ATMs 192 | >>> print(wall_street_atm.next()) 193 | 194 | >>> hsbc.crisis = False # trouble is, even post-crisis the ATM remains empty 195 | >>> print(corner_street_atm.next()) 196 | 197 | >>> brand_new_atm = hsbc.create_atm() # build a new one to get back in business 198 | >>> for cash in brand_new_atm: 199 | ... print cash 200 | $100 201 | $100 202 | $100 203 | $100 204 | $100 205 | $100 206 | $100 207 | $100 208 | $100 209 | ... 210 | 211 | 它可以有利于各种事情,如:控制对于资源的访问。 212 | 213 | ###迭代工具,你最好的朋友 214 | 215 | `itertools`模块有一些处理可迭代对象的专用方法。你是否曾经希望复制一个生成器?链接两个生成器?用一行代码把嵌套列表中的值进行分组?在无需创建另一个列表进行`Map/Zip`? 216 | 217 | 那么,`import itertools`吧。 218 | 219 | 一个例子,让我们看看4匹赛马的抵达顺序: 220 | 221 | >>> horses = [1, 2, 3, 4] 222 | >>> races = itertools.permutations(horses) 223 | >>> print(races) 224 | 225 | >>> print(list(itertools.permutations(horses))) 226 | [(1, 2, 3, 4), 227 | (1, 2, 4, 3), 228 | (1, 3, 2, 4), 229 | (1, 3, 4, 2), 230 | (1, 4, 2, 3), 231 | (1, 4, 3, 2), 232 | (2, 1, 3, 4), 233 | (2, 1, 4, 3), 234 | (2, 3, 1, 4), 235 | (2, 3, 4, 1), 236 | (2, 4, 1, 3), 237 | (2, 4, 3, 1), 238 | (3, 1, 2, 4), 239 | (3, 1, 4, 2), 240 | (3, 2, 1, 4), 241 | (3, 2, 4, 1), 242 | (3, 4, 1, 2), 243 | (3, 4, 2, 1), 244 | (4, 1, 2, 3), 245 | (4, 1, 3, 2), 246 | (4, 2, 1, 3), 247 | (4, 2, 3, 1), 248 | (4, 3, 1, 2), 249 | (4, 3, 2, 1)] 250 | 251 | ###理解迭代的内在机制 252 | 253 | 迭代是一个过程,必然包括可迭代对象(实现`__iter__()`方法)和迭代器(实现`__next__()`方法)。可迭代对象是可以获得迭代器的任何对象。迭代器允许你对可迭代对象进行迭代。 254 | 255 | ##答案 2 256 | 257 | ###深刻理解yield的捷径 258 | 259 | (关于[Grokking](https://en.wikipedia.org/wiki/Grok)) 260 | 261 | 当你看到一个用yield语句的函数时,应用这个简单的技巧来了解将会发生的情况: 262 | 263 | 1. 在函数的开始处插入一行`result = []`。 264 | 2. 把每一处yield语句替换为`result.append(expr)`。 265 | 3. 在函数的末端插入一行`return result`。 266 | 4. 耶!再也没有用yield语句了。阅读并理解代码。 267 | 5. 把这个函数与初始定义进行比较。 268 | 269 | 这个技巧可能会使你对函数背后的逻辑有所了解,但使用yield和使用列表的函数执行起来是有着显著的不同。在很多情况下,使用yield会使得内存效率更高、更快。在其他情况下,即使原函数运行良好,这个技巧也会使你陷入死循环中。继续阅读以便加深了解… 270 | 271 | ###不要把你的可迭代对象、迭代器和生成器弄混 272 | 273 | 首先,迭代器协议。当你书写下面内容的时候 274 | 275 | for x in mylist: 276 | ...loop body... 277 | 278 | Python执行以下两个步骤: 279 | 280 | 1. 获取mylist的迭代器:调用`iter(mylist)`->返回一个带有`next()`方法的对象(或者在Python 3中返回`__next__()`)。(大多数人忘记告诉你这一步) 281 | 2. 循环遍历迭代器:继续调用在步骤1返回的迭代器的`next()`方法。`next()`的返回值被赋给`x`,并且循环体也在运行。如果在`next()`中抛出`StopIteration`异常,就意味着在迭代器中没有更多的值了,循环结束了。 282 | 283 | 事实上,每当Python需要循环遍历某对象的内容时,它就会执行上述两个步骤。所以它可能是一个for循环,但它也可能是像`otherlist.extend(mylist)`这样的代码(其中otherlist是一个Python列表)。 284 | 285 | 这里的mylist是一个可迭代对象,因为它执行了迭代器协议。在一个自定义的类中,你可以使用`__iter__()`方法来让你的实例成为可迭代对象。此方法应该返回到一个迭代器。迭代器是含有`next()`方法的对象。可以在同一个类中执行`__iter__()`和`next()`,并让`__iter__()`结果返回self。上述做法只适用于简单的情况。当你想要让两个迭代器在同一时间对同一对象进行循环的时候,这个做法就不能奏效了。 286 | 287 | 这就是迭代器协议,许多对象都执行这个协议: 288 | 289 | 1. 列表、字典、元组、集合、文件。 290 | 2. 自定义类中的`__iter__()`。 291 | 3. 生成器。 292 | 293 | 注意,for循环不知道它所处理的是什么类型的对象,它只是遵循了迭代器协议,并且只要是调用了`next()`,它就会遍历所有内容。列表会一个一个地返回到其元素,字典一个一个地返回键,文件一行一行地返回每行内容,生成器返回…这就是yield起作用的地方: 294 | 295 | def f123(): 296 | yield 1 297 | yield 2 298 | yield 3 299 | 300 | for item in f123(): 301 | print item 302 | 303 | 如果你在`f123()`中没有使用yield语句,而是使用了三个return 语句,那么只有第一个会被执行,函数将会退出。但`f123()`不是普通的函数。当你调用`f123()`的时候,它不会到返回到yield语句中的任何一个值!它返回到一个生成器对象。此外,该函数并没有真正退出,它进入了一个挂起(暂停)状态。当for 循环尝试对生成器对象进行循环时,该函数将从它的挂起状态恢复运行,直到下一个yield语句,并同前运行。这种情况一直持续到函数退出为止,最后,生成器就会抛出`StopIteration`异常,循环也随之结束。 304 | 305 | 因此,生成器对象有点儿像适配器。它的一端展示了迭代器协议,利用`__iter__()`和`next()`方法保持for循环的畅通。然而,在另一端,它所运行的函数只能够支持它获取下一个值,并把它返回到挂起模式。 306 | 307 | ###为什么要使用生成器? 308 | 309 | 通常,你在写代码时,不使用生成器也能实现相同的逻辑。一个选择是使用我之前提到过的临时列表的“把戏”。这种做法并非在所有的情况下都适用。例如,如果你遇到了死循环,或者当你有一个很长的列表时,它可能会导致内存使用效率低下。另一种方法是使用一个新的可迭代的类型。`SomethingIter`适用于实例成员,并在它的`next()` 或者Python 3中的`__next__()`方法中执行下一个逻辑步骤。根据逻辑,在`next()`方法内部的代码可能看起来很复杂,也容易出现错误。生成器可以为这种情况提供一个干净且容易的解决方案。 310 | 311 | ------- 312 | 313 | 打赏帐号:qiwsir@126.com(支付宝),qiwsir(微信号) 314 | -------------------------------------------------------------------------------- /302.md: -------------------------------------------------------------------------------- 1 | #Python中的元类是什么? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python 4 | 5 | ##问题: 6 | 7 | 什么是元类?使用它们能做什么? 8 | 9 | ##答案 1 10 | 11 | 元类是类的一种。正如类定义了实例功能,元类也定义了类的功能。类是元类的实例。 12 | 13 | 在Python中你可以随意调用元类(参考[Jerub的回答](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/100037#100037)),实际上更有用的方法是使其本身成为一个真正的类。type是Python中常用的元类。你可能觉得奇怪,是的,type本身就是一个类,而且它就是type类型。你无法在Python中重新创造出完全像type这样的东西,但Python提供了一个小把戏。你只需要把type作为子类,就可以在Python中创建自己的元类。 14 | 15 | 元类是最常用的一类工厂。就像你通过调用类来创建类实例,Python也是通过调用元类来创建一个新类(当它执行`class`语句的时候),结合常规的 `__init__`和`__new__`方法,元类可以允许你在创建类的时候做一些“额外的事情”,like registering the new class with some registry(暂时不知道这句话的含义,不知道怎么翻译,字面意思是:就像用某个注册表来注册新的类那样),甚至可以用别的东西完全代替已有的类。 16 | 17 | 当Python执行`class`语句时,它首先把整个的class语句作为一个正常的代码块来执行。由此产生的命名空间(一个字典)具有待定类的属性。元类取决于待定类的基类(元类是具有继承性的)、或待定类的`__metaclass__`属性(如果有的话)或`__metaclass__`全局变量。接下来,用类的名称、基类和属性调用元类,从而把元类实例化。 18 | 19 | 然而,元类实际上定义的一个类的类型,而不只是类工厂,所以你可以用元类来做更多的事情。例如,你可以定义元类的一般方法。这些元类方法和类方法有相似之处,因为它们可以被没有实例化的类调用。但这些元类方法和类方法也有不同之处,元类方法不能在类的实例中被调用。`type.__subclasses__()`是关于type的一个方法。你也可以定义常规的“魔法”函数,如`__add__`, `__iter__`和`__getattr__`,以便实现或修改类的功能。 20 | 21 | 摘抄一个例子: 22 | 23 | def make_hook(f): 24 | """Decorator to turn 'foo' method into '__foo__'""" 25 | f.is_hook = 1 26 | return f 27 | 28 | class MyType(type): 29 | def __new__(cls, name, bases, attrs): 30 | 31 | if name.startswith('None'): 32 | return None 33 | 34 | # Go over attributes and see if they should be renamed. 35 | newattrs = {} 36 | for attrname, attrvalue in attrs.iteritems(): 37 | if getattr(attrvalue, 'is_hook', 0): 38 | newattrs['__%s__' % attrname] = attrvalue 39 | else: 40 | newattrs[attrname] = attrvalue 41 | 42 | return super(MyType, cls).__new__(cls, name, bases, newattrs) 43 | 44 | def __init__(self, name, bases, attrs): 45 | super(MyType, self).__init__(name, bases, attrs) 46 | 47 | # classregistry.register(self, self.interfaces) 48 | print "Would register class %s now." % self 49 | 50 | def __add__(self, other): 51 | class AutoClass(self, other): 52 | pass 53 | return AutoClass 54 | # Alternatively, to autogenerate the classname as well as the class: 55 | # return type(self.__name__ + other.__name__, (self, other), {}) 56 | 57 | def unregister(self): 58 | # classregistry.unregister(self) 59 | print "Would unregister class %s now." % self 60 | 61 | class MyObject: 62 | __metaclass__ = MyType 63 | 64 | 65 | class NoneSample(MyObject): 66 | pass 67 | 68 | # Will print "NoneType None" 69 | print type(NoneSample), repr(NoneSample) 70 | 71 | class Example(MyObject): 72 | def __init__(self, value): 73 | self.value = value 74 | @make_hook 75 | def add(self, other): 76 | return self.__class__(self.value + other.value) 77 | 78 | # Will unregister the class 79 | Example.unregister() 80 | 81 | inst = Example(10) 82 | # Will fail with an AttributeError 83 | #inst.unregister() 84 | 85 | print inst + inst 86 | class Sibling(MyObject): 87 | pass 88 | 89 | ExampleSibling = Example + Sibling 90 | # ExampleSibling is now a subclass of both Example and Sibling (with no 91 | # content of its own) although it will believe it's called 'AutoClass' 92 | print ExampleSibling 93 | print ExampleSibling.__mro__ 94 | shareedit 95 | 96 | ##答案 2 97 | 98 | ###作为对象的类 99 | 100 | 在理解元类之前,你需要掌握Python中的类。Python对于类的定义很特别,这是从Smalltalk语言中借鉴来的。 101 | 102 | 在大多数语言中,类只是描述如何创建一个对象的代码段。Python中的类大体上也是如此: 103 | 104 | >>> class ObjectCreator(object): 105 | ... pass 106 | ... 107 | 108 | >>> my_object = ObjectCreator() 109 | >>> print(my_object) 110 | <__main__.ObjectCreator object at 0x8974f2c> 111 | 112 | 而Python中的类并不是仅限于此。它的类也是对象。 113 | 114 | 是的,对象。 115 | 116 | 当你使用关键字class时,Python执行它并创建一个对象。下面是有关的指令 117 | 118 | >>> class ObjectCreator(object): 119 | ... pass 120 | ... 121 | 122 | 这个对象(类)本身就能够创建一些对象(实例),这就是为什么它是类。 123 | 124 | 但它仍然是一个对象,因而: 125 | 126 | - 你可以将它分配给一个变量 127 | - 你可以复制它 128 | - 你可以增加它的属性 129 | - 你可以把它作为一个功能参数来用 130 | 131 | 例如: 132 | 133 | >>> print(ObjectCreator) # you can print a class because it's an object 134 | 135 | >>> def echo(o): 136 | ... print(o) 137 | ... 138 | >>> echo(ObjectCreator) # you can pass a class as a parameter 139 | 140 | >>> print(hasattr(ObjectCreator, 'new_attribute')) 141 | False 142 | >>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class 143 | >>> print(hasattr(ObjectCreator, 'new_attribute')) 144 | True 145 | >>> print(ObjectCreator.new_attribute) 146 | foo 147 | >>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable 148 | >>> print(ObjectCreatorMirror.new_attribute) 149 | foo 150 | >>> print(ObjectCreatorMirror()) 151 | <__main__.ObjectCreator object at 0x8997b4c> 152 | Creating classes dynamically 153 | 154 | ###类的动态创建 155 | 156 | 既然类是对象,你就能动态地创建它们,就像创建任何对象那样。 157 | 158 | 首先,你可以在一个使用class的函数中创建类: 159 | 160 | >>> def choose_class(name): 161 | ... if name == 'foo': 162 | ... class Foo(object): 163 | ... pass 164 | ... return Foo # return the class, not an instance 165 | ... else: 166 | ... class Bar(object): 167 | ... pass 168 | ... return Bar 169 | ... 170 | >>> MyClass = choose_class('foo') 171 | >>> print(MyClass) # the function returns a class, not an instance 172 | 173 | >>> print(MyClass()) # you can create an object from this class 174 | <__main__.Foo object at 0x89c6d4c> 175 | 176 | 但它并不是动态的,因为你还是要自己写出整个类。 177 | 178 | 类是对象,它们必须由某种东西产生。 179 | 180 | 当你使用关键字class时,Python会自动创建该对象。但是,与Python中的大多数东西一样,它给你提供了一个手工操作的方法。 181 | 182 | 还记得type函数吗?这个一个好用的旧函数,它能让你了解一个对象的类型: 183 | 184 | >>> print(type(1)) 185 | 186 | >>> print(type("1")) 187 | 188 | >>> print(type(ObjectCreator)) 189 | 190 | >>> print(type(ObjectCreator())) 191 | 192 | 193 | type有着完全不同的能力,它还可以动态地创建类。type可以把对于类的描述作为参数,并返回一个类。 194 | 195 | (同样的函数根据你传入的参数而有完全不同的用途。我知道这看起来有点怪。这是因为Python向后兼容。) 196 | 197 | type是这样应用的: 198 | 199 | 例如: 200 | 201 | >>> class MyShinyClass(object): 202 | ... pass 203 | 204 | 可以这样子来进行手动创建 205 | 206 | >>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object 207 | >>> print(MyShinyClass) 208 | 209 | >>> print(MyShinyClass()) # create an instance with the class 210 | <__main__.MyShinyClass object at 0x8997cec> 211 | 212 | 你会注意到,我们使用“MyShinyClass”作为类的名称,并把它作为类所引用的变量。他们可以是不同的,但没有理由把事情复杂化。 213 | 214 | type接受字典对于类属性的定义。所以: 215 | 216 | >>> class Foo(object): 217 | ... bar = True 218 | 219 | 可以被转化为: 220 | 221 | >>> Foo = type('Foo', (), {'bar':True}) 222 | 223 | 并且被用作一个常规的类: 224 | 225 | >>> print(Foo) 226 | 227 | >>> print(Foo.bar) 228 | True 229 | >>> f = Foo() 230 | >>> print(f) 231 | <__main__.Foo object at 0x8a9b84c> 232 | >>> print(f.bar) 233 | True 234 | 235 | 当然,你也可以继承它,即: 236 | 237 | >>> class FooChild(Foo): 238 | ... pass 239 | 240 | 可以转化为: 241 | 242 | >>> FooChild = type('FooChild', (Foo,), {}) 243 | >>> print(FooChild) 244 | 245 | >>> print(FooChild.bar) # bar is inherited from Foo 246 | True 247 | 248 | 最终,你会想把一些方法添加到你的类中。需要用一个适当的识别标志来定义一个函数,并将其指定为一个属性。 249 | 250 | >>> def echo_bar(self): 251 | ... print(self.bar) 252 | ... 253 | >>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar}) 254 | >>> hasattr(Foo, 'echo_bar') 255 | False 256 | >>> hasattr(FooChild, 'echo_bar') 257 | True 258 | >>> my_foo = FooChild() 259 | >>> my_foo.echo_bar() 260 | True 261 | 262 | 你现在明白了:在Python中,类就是对象,你可以动态地创建类。 263 | 264 | 这就是关键字class在Python中的应用,它是通过使用元类来发挥作用。 265 | 266 | ###元类是什么 267 | 268 | 元类是用来创建类的东西。 269 | 270 | 你通过定义类来创建对象,对吧? 271 | 272 | 但我们知道Python的类就是对象。 273 | 274 | 元类用于创建这些对象,元类是类的类,你可以这样来描述它们: 275 | 276 | MyClass = MetaClass() 277 | MyObject = MyClass() 278 | 279 | 你已经看到了type可以这样来用: 280 | 281 | MyClass = type('MyClass', (), {}) 282 | 283 | 这是因为type实际上是一个元类,作为元类的type在Python中被用于在后台创建所有的类。 284 | 285 | 现在你感到疑惑的是为什么这里是小写的type,而不是大写的Type? 286 | 287 | 我想这是为了与创建字符串对象的类str和创建整数对象的类int在写法上保持一致。type只是用于创建类的类。 288 | 289 | 你可以通过检查`__class__`的属性来看清楚。 290 | 291 | Python中的一切,我的意思是所有的东西,都是对象。包括整数、字符串、函数和类。所有这些都是对象。所有这些都是由一个类创建的: 292 | 293 | >>> age = 35 294 | >>> age.__class__ 295 | 296 | >>> name = 'bob' 297 | >>> name.__class__ 298 | 299 | >>> def foo(): pass 300 | >>> foo.__class__ 301 | 302 | >>> class Bar(object): pass 303 | >>> b = Bar() 304 | >>> b.__class__ 305 | 306 | 307 | 现在,任何`__class__`中的特定`__class__`是什么? 308 | 309 | >>> age.__class__.__class__ 310 | 311 | >>> name.__class__.__class__ 312 | 313 | >>> foo.__class__.__class__ 314 | 315 | >>> b.__class__.__class__ 316 | 317 | 318 | 所以,元类只是用于创建类对象的东西。 319 | 320 | 如果你愿意,你可以把它称为“类工厂”。 321 | 322 | type是Python中内建元类,当然,你也可以创建你自己的元类。 323 | 324 | ### `__metaclass__`的属性 325 | 326 | 当你创建类的时候,可以添加一个`__metaclass__`属性: 327 | 328 | class Foo(object): 329 | __metaclass__ = something... 330 | [...] 331 | 332 | 如果你这样做,Python会使用元类来创建Foo这个类。 333 | 334 | 小心,这是棘手的。 335 | 336 | 这是你是首次创建`class Foo(object)`,但是类对象Foo在内存中还没有被创建。 337 | 338 | Python会在类定义中寻找`__metaclass__`。如果找到它,Python会用它来创建对象类Foo。如果没有找到它,Python将使用type来创建这个类。 339 | 340 | 把上面的话读几遍。 341 | 342 | 当你写下: 343 | 344 | class Foo(Bar): 345 | pass 346 | 347 | Python会实现以下功能: 348 | 349 | Foo有没有`__metaclass__`的属性? 350 | 351 | 如果有,通过借鉴`__metaclass__`,用Foo这个名字在内存中创建一个类对象(我说的是一个类对象,记住我的话)。 352 | 353 | 如果Python找不到`__metaclass__`,它会在模块层级寻找`__metaclass__`,并尝试做同样的事情(但这只适用于不继承任何东西的类,基本上是旧式类)。 354 | 355 | 如果它根本找不到任何`__metaclass__`,它将使用Bar(第一个父类)自己的元类(这可能是默认的type)来创建类对象。 356 | 357 | 小心点,`__metaclass__`属性不会被继承,而父类的元类(`Bar.__class__`)将会被继承。如果Bar所用的`__metaclass__`属性是用`type()`来创建Bar(而不是`type.__new__()`),它的子类不会继承这种功能。 358 | 359 | 现在最大的问题是,你可以在`__metaclass__`中写些什么? 360 | 361 | 答案是:可以创建类的东西。 362 | 363 | 什么可以创建类?type,或者父类。 364 | 365 | ###自定义元类 366 | 367 | 一个元类的主要目的是当它被创建时,这个类可以自动改变。 368 | 369 | 通常在API中,可以创建一个元类,以之匹配于当前的内容。 370 | 371 | 想象一个愚蠢的例子:模块中的所有类的属性都应该用大写字母来写。你有几种方法,其中的一种方法就是在模块层次上设置`__metaclass__`。 372 | 373 | 这样,这个模块中所有的类都将使用这个元类来创建,我们只需要告诉元类把所有属性改为大写。 374 | 375 | 幸运的是,`__metaclass__`实际上可以任意调用,它并不需要成为一个正式的类(我知道,名字中带有“class”字样的东西未必就是类,想想看吧…但这是有益的)。 376 | 377 | 因此,我们将通过使用函数来举一个简单的例子。 378 | 379 | # the metaclass will automatically get passed the same argument 380 | # that you usually pass to `type` 381 | def upper_attr(future_class_name, future_class_parents, future_class_attr): 382 | """ 383 | Return a class object, with the list of its attribute turned into uppercase. 384 | """ 385 | 386 | # pick up any attribute that doesn't start with '__' and uppercase it 387 | uppercase_attr = {} 388 | for name, val in future_class_attr.items(): 389 | if not name.startswith('__'): 390 | uppercase_attr[name.upper()] = val 391 | else: 392 | uppercase_attr[name] = val 393 | 394 | # let `type` do the class creation 395 | return type(future_class_name, future_class_parents, uppercase_attr) 396 | 397 | __metaclass__ = upper_attr # this will affect all classes in the module 398 | 399 | class Foo(): # global __metaclass__ won't work with "object" though 400 | # but we can define __metaclass__ here instead to affect only this class 401 | # and this will work with "object" children 402 | bar = 'bip' 403 | 404 | print(hasattr(Foo, 'bar')) 405 | # Out: False 406 | print(hasattr(Foo, 'BAR')) 407 | # Out: True 408 | 409 | f = Foo() 410 | print(f.BAR) 411 | # Out: 'bip' 412 | 413 | 现在,让我们完全照做,但使用一个真的类作为元类: 414 | 415 | # remember that `type` is actually a class like `str` and `int` 416 | # so you can inherit from it 417 | class UpperAttrMetaclass(type): 418 | # __new__ is the method called before __init__ 419 | # it's the method that creates the object and returns it 420 | # while __init__ just initializes the object passed as parameter 421 | # you rarely use __new__, except when you want to control how the object 422 | # is created. 423 | # here the created object is the class, and we want to customize it 424 | # so we override __new__ 425 | # you can do some stuff in __init__ too if you wish 426 | # some advanced use involves overriding __call__ as well, but we won't 427 | # see this 428 | def __new__(upperattr_metaclass, future_class_name, future_class_parents, future_class_attr): 429 | 430 | uppercase_attr = {} 431 | for name, val in future_class_attr.items(): 432 | if not name.startswith('__'): 433 | uppercase_attr[name.upper()] = val 434 | else: 435 | uppercase_attr[name] = val 436 | 437 | return type(future_class_name, future_class_parents, uppercase_attr) 438 | 439 | 但这不是真正的面向对象编程。我们直接调用type,我们无需覆盖或调用父类`__new__`。让我们着手吧: 440 | 441 | class UpperAttrMetaclass(type): 442 | 443 | def __new__(upperattr_metaclass, future_class_name, future_class_parents, future_class_attr): 444 | 445 | uppercase_attr = {} 446 | for name, val in future_class_attr.items(): 447 | if not name.startswith('__'): 448 | uppercase_attr[name.upper()] = val 449 | else: 450 | uppercase_attr[name] = val 451 | 452 | # reuse the type.__new__ method 453 | # this is basic OOP, nothing magic in there 454 | return type.__new__(upperattr_metaclass, future_class_name, future_class_parents, uppercase_attr) 455 | 456 | 你可能已经注意到额外的参数`upperattr_metaclass`,它没有什么特别之处:`__new__`以`upperattr_metaclass`为第一参数,并且在`upperattr_metaclass`中被定义。就像你把self作为实例的第一个参数那样,或者作为类方法的第一个参数。 457 | 458 | 当然,我在这里为了清晰起见,使用了一个很长的名称,但就像self一样,所有的参数都有习惯的名称。所以,在开发实践中所写的元类看起来是这样的: 459 | 460 | class UpperAttrMetaclass(type): 461 | 462 | def __new__(cls, clsname, bases, dct): 463 | 464 | uppercase_attr = {} 465 | for name, val in dct.items(): 466 | if not name.startswith('__'): 467 | uppercase_attr[name.upper()] = val 468 | else: 469 | uppercase_attr[name] = val 470 | 471 | return type.__new__(cls, clsname, bases, uppercase_attr) 472 | 473 | 我们可以用super使它更清楚,这样将缓解继承(因为,是的,你可以拥有元类,继承metaclasses,继承type): 474 | 475 | class UpperAttrMetaclass(type): 476 | 477 | def __new__(cls, clsname, bases, dct): 478 | 479 | uppercase_attr = {} 480 | for name, val in dct.items(): 481 | if not name.startswith('__'): 482 | uppercase_attr[name.upper()] = val 483 | else: 484 | uppercase_attr[name] = val 485 | 486 | return super(UpperAttrMetaclass, cls).__new__(cls, clsname, bases, uppercase_attr) 487 | 488 | 就是这样。关于元类真的是没有更多要讲的了。 489 | 490 | 使用元类的代码复杂的原因并不在于元类,那是因为你通常用元类来实现一些奇怪的功能,而这些功能要依靠自省、继承、变量,如:`__dict__`等。 491 | 492 | 的确,元类对于“魔法”特别有用,这些事务是复杂的,但元类本身很简单: 493 | 494 | - 拦截类的创建 495 | - 修改类 496 | - 返回修改后的类 497 | 498 | ###你为什么要使用元类而不是函数? 499 | 500 | `__metaclass__`可以被任意调用。既然类明显更复杂,你为什么还要使用它呢? 501 | 502 | 这样做有几个理由: 503 | 504 | - 目的明确。当你读`UpperAttrMetaclass(type)`时,你知道要遵循的是什么。 505 | - 可以使用面向对象编程。元类可以继承元类、重写父类的方法。元类甚至可以使用元类。 506 | - 可以优化代码。你从不为像上面例子中琐碎的东西而使用元类。它通常用于复杂的东西。在一个类中有多种方法并且将它们优化组合,是非常有价值的,使得代码可读性更强。 507 | - 你可能喜欢使用`__new__`,`__init__`和`__call__`。它们能帮你实现不同的功能。尽管你通常可以用`__new__`来实现所有的功能,有些人还是更喜欢使用`__init__`。 508 | - 这些被称为元类。可恶!它肯定意味着什么! 509 | 510 | 你为什么会使用元类? 511 | 512 | 现在的大问题是:为什么你会使用一些复杂难懂、容易出错的特性? 513 | 514 | 嗯,通常你不会这样做: 515 | 516 | >元类是更深层次的魔法,超过99%的用户不需要担心。不要怀疑你是否需要元类(那些真正需要元类的人对此确定无疑,并且不需要解释为什么)。 517 | 518 | >——Python专家蒂姆﹒彼得斯 519 | 520 | 元类的主要使用案例是创建API。一个典型的例子就是Django ORM。 521 | 522 | 它允许你定义类似这样的东西: 523 | 524 | class Person(models.Model): 525 | name = models.CharField(max_length=30) 526 | age = models.IntegerField() 527 | 528 | 但如果你这样做: 529 | 530 | guy = Person(name='bob', age='35') 531 | print(guy.age) 532 | 533 | 它不会返回到一个`IntegerField`对象。它会返回到一个int,甚至可以直接从数据库读取。 534 | 535 | 这是可以实现的,因为`models.Model`定义了`__metaclass__`。它使用魔法把你刚才用简单语句定义的Person转化成一个复杂的钩子连接到数据库字段。 536 | 537 | 通过显示一个简单的API和元类,Django使复杂的东西看起来简单,再从API重构代码去完成真正的幕后工作。 538 | 539 | ###最后的话 540 | 541 | 首先,你知道,类是可以创建实例的对象。 542 | 543 | 事实上,类本身就是实例。在元类中 544 | 545 | >>> class Foo(object): pass 546 | >>> id(Foo) 547 | 142630324 548 | 549 | 在Python中,一切都是对象,它们都是类的实例或元类的实例。 550 | 551 | 但是type除外。 552 | 553 | type实际上是自己的元类。你无法在纯粹的Python中复制它,所以只能在实施层面做点小把戏。 554 | 555 | 其次,元类是复杂的。你可能不想把它们用于非常简单的类。你可以用两种不同的技术来改变类: 556 | - [猴子补丁monkey patching](http://en.wikipedia.org/wiki/Monkey_patch) 557 | - 类装饰器 558 | 559 | 当你需要改变类的时候,99%的情况下,使用它们是明智之举。 560 | 561 | 但99%的时间,你根本不需要改变类。 562 | 563 | ------- 564 | 565 | 打赏帐号:qiwsir@126.com(支付宝),qiwsir(微信号) 566 | -------------------------------------------------------------------------------- /303.md: -------------------------------------------------------------------------------- 1 | #怎样在Python中创建函数装饰器链? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python 4 | 5 | ##问题: 6 | 7 | 我怎样在Python中创建能实现以下功能的两个装饰器? 8 | 9 | @makebold 10 | @makeitalic 11 | def say(): 12 | return "Hello" 13 | 14 | 返回的是: 15 | 16 | Hello 17 | 18 | 我不想在实际的应用程序中以这种方式来创建HTML,只是想了解装饰器和装饰器链是怎么回事。 19 | 20 | ##答案 1: 21 | 22 | 查看[参考文献](https://docs.python.org/2/reference/compound_stmts.html#function)来了解装饰器的应用。这是你所要找的内容: 23 | 24 | def makebold(fn): 25 | def wrapped(): 26 | return "" + fn() + "" 27 | return wrapped 28 | 29 | def makeitalic(fn): 30 | def wrapped(): 31 | return "" + fn() + "" 32 | return wrapped 33 | 34 | @makebold 35 | @makeitalic 36 | def hello(): 37 | return "hello world" 38 | 39 | print hello() ## returns "hello world" 40 | 41 | ##答案 2: 42 | 43 | ###装饰器基础知识 44 | 45 | **Python中的函数就是对象** 46 | 47 | 要了解装饰器,你首先必须深知Python中的函数就是对象。这是重要的。让我们通过一个简单的例子来看看为什么: 48 | 49 | def shout(word="yes"): 50 | return word.capitalize()+"!" 51 | 52 | print shout() 53 | # outputs : 'Yes!' 54 | 55 | # 作为对象,你可以把这个函数赋值给一个变量,像任何其他对象一样 56 | 57 | scream = shout 58 | 59 | #注意:我们不使用圆括号:不调用函数,我们是把函数“shout”赋给变量“scream”。这意味着你可以从“scream”中调用“shout”: 60 | 61 | print scream() 62 | # outputs : 'Yes!' 63 | 64 | # 不仅如此,这意味着你可以删除旧的名字'shout',并且仍然可以用'scream'调用这个函数。 65 | 66 | del shout 67 | try: 68 | print shout() 69 | except NameError, e: 70 | print e 71 | # outputs: "name 'shout' is not defined" 72 | print scream() 73 | # outputs: 'Yes!' 74 | 75 | 好的,记住上述内容。我们很快就要用到它。 76 | 77 | Python函数的另一个有趣的特性是它们可以在另一个函数里被定义! 78 | 79 | def talk(): 80 | 81 | # 你可以在"talk"中定义一个动态函数… 82 | def whisper(word="yes"): 83 | return word.lower()+"..." 84 | 85 | # 然后马上就能使用它! 86 | print whisper() 87 | 88 | # 如果你每次调用"talk"的时候,"talk"都被定义为"whisper",那么"whisper"就在"talk"中被调用。 89 | 90 | talk() 91 | # outputs: 92 | # "yes..." 93 | 94 | # 但"whisper"不存在于"talk"之外: 95 | 96 | try: 97 | print whisper() 98 | except NameError, e: 99 | print e 100 | # outputs : "name 'whisper' is not defined"* 101 | # Python的函数是对象 102 | 103 | **函数引用** 104 | 105 | 好吧,还在这儿?现在有趣的部分是… 106 | 107 | 你已经看到了函数就是对象。因此,函数: 108 | 109 | - 可以被赋值给一个变量 110 | - 可以在另一个函数中定义 111 | 112 | 这意味着一个函数可以返回另一个函数。看一看!☺ 113 | 114 | def getTalk(kind="shout"): 115 | 116 | # 定义动态函数 117 | def shout(word="yes"): 118 | return word.capitalize()+"!" 119 | 120 | def whisper(word="yes") : 121 | return word.lower()+"..."; 122 | 123 | # 然后我们返回到其中一个 124 | if kind == "shout": 125 | # 不使用"()",我们不是在调用函数, 126 | # 是在返回函数对象 127 | return shout 128 | else: 129 | return whisper 130 | 131 | # 你怎么使用这个奇怪的工具? 132 | # 获取函数并将它赋给变量 133 | talk = getTalk() 134 | 135 | # 你可以看到这里的"talk"是一个函数对象: 136 | print talk 137 | # outputs : 138 | 139 | # 此函数所返回的就是这个对象: 140 | print talk() 141 | #outputs : Yes! 142 | 143 | # 如果你感到亢奋,你甚至可以直接使用它: 144 | print getTalk("whisper")() 145 | #outputs : yes... 146 | 147 | 但是,等等…还有更多! 148 | 149 | 如果你可以返回一个函数,你就可以把一个函数当作参数: 150 | 151 | def doSomethingBefore(func): 152 | print "I do something before then I call the function you gave me" 153 | print func() 154 | 155 | doSomethingBefore(scream) 156 | #outputs: 157 | #I do something before then I call the function you gave me 158 | #Yes! 159 | 160 | 好的,你已经看到了理解装饰器所需要的所有知识。你看,装饰器是“包装器”。这意味着装饰器可以使你在它所装饰的函数之前和之后运行代码,而无需修改函数本身。 161 | 162 | **装饰器的手动操作** 163 | 164 | 这样来进行装饰器的手动操做: 165 | 166 | # 装饰器是一个函数,它把另一个函数作为参数 167 | 168 | def my_shiny_new_decorator(a_function_to_decorate): 169 | 170 | # 函数里面,装饰器定义了一个动态函数:the wrapper。 171 | # 这个函数包含原函数,因此它可以在原函数之前和之后运行代码。 172 | def the_wrapper_around_the_original_function(): 173 | 174 | # 把你希望在原函数被调用之前就执行的代码放在这里 175 | 176 | print "Before the function runs" 177 | 178 | # 调用函数(使用括号) 179 | a_function_to_decorate() 180 | 181 | # 把你希望在原函数被调用之后才执行的代码放在这里 182 | 183 | print "After the function runs" 184 | 185 | # 这时候,"a_function_to_decorate"从未被执行。 186 | # 回到我们刚才创建的包装器函数。 187 | # 包装器中包含在原函数被执行之前和之后的函数和代码。它是现成的! 188 | return the_wrapper_around_the_original_function 189 | 190 | #现在想象你创建一个你不想再改动的函数。 191 | def a_stand_alone_function(): 192 | print "I am a stand alone function, don't you dare modify me" 193 | 194 | a_stand_alone_function() 195 | #outputs: I am a stand alone function, don't you dare modify me 196 | 197 | #你可以装饰它,以便扩展它的功能。 198 | #只需要把它传递给装饰器,装饰器就会把它动态地装进任何你想要的代码中, 199 | #并且为你返回一个新的可用的函数: 200 | 201 | a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function) 202 | a_stand_alone_function_decorated() 203 | #outputs: 204 | #Before the function runs 205 | #I am a stand alone function, don't you dare modify me 206 | #After the function runs 207 | 208 | 209 | 现在,你可能希望你每次调用`a_stand_alone_function`的时候,实际上就是在调用`a_stand_alone_function_decorated`。这很容易,你只需要借助`my_shiny_new_decorator`返回的函数覆盖`a_stand_alone_function`: 210 | 211 | a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function) 212 | a_stand_alone_function() 213 | 214 | #outputs: 215 | #Before the function runs 216 | #I am a stand alone function, don't you dare modify me 217 | #After the function runs 218 | 219 | # 你猜会怎么样?这正是装饰器所实现的功能! 220 | 221 | **装饰器揭秘** 222 | 223 | 前面的例子中使用了装饰器句法: 224 | 225 | @my_shiny_new_decorator 226 | def another_stand_alone_function(): 227 | print "Leave me alone" 228 | 229 | another_stand_alone_function() 230 | #outputs: 231 | #Before the function runs 232 | #Leave me alone 233 | #After the function runs 234 | 235 | 是的,就这些,就是这么简单。@decorator只是一个捷径: 236 | 237 | another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function) 238 | 239 | 装饰器是装饰器设计模式[decorator design pattern](http://en.wikipedia.org/wiki/Decorator_pattern)的Python语言的变体。在Python中,有几种经典的嵌套模式来减轻开发的难度(像迭代器那样)。 240 | 241 | 当然,你可以把装饰器累积起来: 242 | 243 | def bread(func): 244 | def wrapper(): 245 | print "" 246 | func() 247 | print "<\______/>" 248 | return wrapper 249 | 250 | def ingredients(func): 251 | def wrapper(): 252 | print "#tomatoes#" 253 | func() 254 | print "~salad~" 255 | return wrapper 256 | 257 | def sandwich(food="--ham--"): 258 | print food 259 | 260 | sandwich() 261 | # outputs: --ham-- 262 | sandwich = bread(ingredients(sandwich)) 263 | sandwich() 264 | # outputs: 265 | # 266 | # #tomatoes# 267 | # --ham-- 268 | # ~salad~ 269 | #<\______/> 270 | 271 | 使用Python的装饰器句法: 272 | 273 | @bread 274 | @ingredients 275 | def sandwich(food="--ham--"): 276 | print food 277 | 278 | sandwich() 279 | #outputs: 280 | # 281 | # #tomatoes# 282 | # --ham-- 283 | # ~salad~ 284 | #<\______/> 285 | 286 | 装饰器顺序的设置很重要: 287 | 288 | @ingredients 289 | @bread 290 | def strange_sandwich(food="--ham--"): 291 | print food 292 | 293 | strange_sandwich() 294 | #outputs: 295 | ##tomatoes# 296 | # 297 | # --ham-- 298 | #<\______/> 299 | # ~salad~ 300 | 301 | 现在:回答这个问题… 302 | 303 | 作为结论,你可以很容易地领会到如何回答这个问题: 304 | 305 | # 使字体变粗的装饰器 306 | def makebold(fn): 307 | # 装饰器所返回的新函数 308 | def wrapper(): 309 | # 在函数之前和之后插入某些代码 310 | return "" + fn() + "" 311 | return wrapper 312 | 313 | # 斜体字的装饰器 314 | def makeitalic(fn): 315 | # The new function the decorator returns 316 | def wrapper(): 317 | # Insertion of some code before and after 318 | return "" + fn() + "" 319 | return wrapper 320 | 321 | @makebold 322 | @makeitalic 323 | def say(): 324 | return "hello" 325 | 326 | print say() 327 | #outputs: hello 328 | 329 | # This is the exact equivalent to 330 | def say(): 331 | return "hello" 332 | say = makebold(makeitalic(say)) 333 | 334 | 这和下面的函数是完全等价的 335 | 336 | print say() 337 | #outputs: hello 338 | 339 | 你现在可以快乐地离开,或者多花点心思看一看装饰器的高级应用。 340 | 341 | ###装饰器应用的更高等级 342 | 343 | **将参数传递给被装饰的函数** 344 | 345 | # 这不是魔法,你只需要让包装器传递参数: 346 | def a_decorator_passing_arguments(function_to_decorate): 347 | def a_wrapper_accepting_arguments(arg1, arg2): 348 | print "I got args! Look:", arg1, arg2 349 | function_to_decorate(arg1, arg2) 350 | return a_wrapper_accepting_arguments 351 | 352 | # 因为当你调用被装饰器返回的函数时,你就是在调用包装器,把参数传递给包装器会使包装器把函数传递给被装饰的函数 353 | @a_decorator_passing_arguments 354 | def print_full_name(first_name, last_name): 355 | print "My name is", first_name, last_name 356 | 357 | print_full_name("Peter", "Venkman") 358 | # outputs: 359 | #I got args! Look: Peter Venkman 360 | #My name is Peter Venkman 361 | 362 | **装饰方法** 363 | 364 | 关于Python的一个有趣的方面是,方法和函数实际上是一样的。唯一的区别是,方法的第一个参数用于引用当前对象(self)。 365 | 366 | 这意味着你可以用同样的方式为方法创建装饰器!只是要记得把`self`考虑在内: 367 | 368 | def method_friendly_decorator(method_to_decorate): 369 | def wrapper(self, lie): 370 | lie = lie - 3 # very friendly, decrease age even more :-) 371 | return method_to_decorate(self, lie) 372 | return wrapper 373 | 374 | class Lucy(object): 375 | 376 | def __init__(self): 377 | self.age = 32 378 | 379 | @method_friendly_decorator 380 | def sayYourAge(self, lie): 381 | print "I am %s, what did you think?" % (self.age + lie) 382 | 383 | l = Lucy() 384 | l.sayYourAge(-3) 385 | #outputs: I am 26, what did you think? 386 | 387 | 如果你在创建通用装饰器 —— 可以适用于任何函数或方法的装饰器,不管它的参数是什么—— 你只需要使用*args,**kwargs: 388 | 389 | def a_decorator_passing_arbitrary_arguments(function_to_decorate): 390 | # 包装器接受任何参数 391 | def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs): 392 | print "Do I have args?:" 393 | print args 394 | print kwargs 395 | # Then you unpack the arguments, here *args, **kwargs 396 | # If you are not familiar with unpacking, check:http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ 397 | function_to_decorate(*args, **kwargs) 398 | return a_wrapper_accepting_arbitrary_arguments 399 | 400 | @a_decorator_passing_arbitrary_arguments 401 | def function_with_no_argument(): 402 | print "Python is cool, no argument here." 403 | 404 | function_with_no_argument() 405 | #outputs 406 | #Do I have args?: 407 | #() 408 | #{} 409 | #Python is cool, no argument here. 410 | 411 | @a_decorator_passing_arbitrary_arguments 412 | def function_with_arguments(a, b, c): 413 | print a, b, c 414 | 415 | function_with_arguments(1,2,3) 416 | #outputs 417 | #Do I have args?: 418 | #(1, 2, 3) 419 | #{} 420 | #1 2 3 421 | 422 | @a_decorator_passing_arbitrary_arguments 423 | def function_with_named_arguments(a, b, c, platypus="Why not ?"): 424 | print "Do %s, %s and %s like platypus? %s" %\ 425 | (a, b, c, platypus) 426 | 427 | function_with_named_arguments("Bill", "Linus", "Steve", platypus="Indeed!") 428 | #outputs 429 | #Do I have args ? : 430 | #('Bill', 'Linus', 'Steve') 431 | #{'platypus': 'Indeed!'} 432 | #Do Bill, Linus and Steve like platypus? Indeed! 433 | 434 | class Mary(object): 435 | 436 | def __init__(self): 437 | self.age = 31 438 | 439 | @a_decorator_passing_arbitrary_arguments 440 | def sayYourAge(self, lie=-3): # You can now add a default value 441 | print "I am %s, what did you think ?" % (self.age + lie) 442 | 443 | m = Mary() 444 | m.sayYourAge() 445 | # outputs 446 | # Do I have args?: 447 | #(<__main__.Mary object at 0xb7d303ac>,) 448 | #{} 449 | #I am 28, what did you think? 450 | 451 | **把参数传递给装饰器** 452 | 453 | 好,现在你对于把参数传递给装饰器本身有什么看法? 454 | 455 | 这可能有点怪异,因为装饰器必须接受一个函数作为参数。因此,你不能把被装饰的函数的参数直接传递给装饰器。 456 | 457 | 在急着去解决问题之前,让我们写一个小小的提示: 458 | 459 | # 装饰器是普通函数 460 | def my_decorator(func): 461 | print "I am an ordinary function" 462 | def wrapper(): 463 | print "I am function returned by the decorator" 464 | func() 465 | return wrapper 466 | 467 | # 因此,即使没有任何“@”,你也可以调用它 468 | def lazy_function(): 469 | print "zzzzzzzz" 470 | 471 | decorated_function = my_decorator(lazy_function) 472 | #outputs: I am an ordinary function 473 | 474 | # It outputs "I am an ordinary function", because that’s just what you do: 475 | # calling a function. Nothing magic. 476 | 477 | @my_decorator 478 | def lazy_function(): 479 | print "zzzzzzzz" 480 | 481 | #outputs: I am an ordinary function 482 | 483 | 这是完全一样的。`my_decorator`被调用。所以当你使用`@my_decorator`的时候,你就是在告诉Python调用标记为变量`my_decorator`的函数。 484 | 485 | 这是很重要的!你所给出的标签可以直接指向装饰器,或者相反。 486 | 487 | 让我们搞个小把戏。 488 | 489 | def decorator_maker(): 490 | 491 | print "I make decorators! I am executed only once: " + "when you make me create a decorator." 492 | 493 | def my_decorator(func): 494 | 495 | print "I am a decorator! I am executed only when you decorate a function." 496 | 497 | def wrapped(): 498 | print ("I am the wrapper around the decorated function. " 499 | "I am called when you call the decorated function. " 500 | "As the wrapper, I return the RESULT of the decorated function.") 501 | return func() 502 | 503 | print "As the decorator, I return the wrapped function." 504 | 505 | return wrapped 506 | 507 | print "As a decorator maker, I return a decorator" 508 | return my_decorator 509 | 510 | # 让我们创建一个装饰器。它只是一个新函数而已。 511 | new_decorator = decorator_maker() 512 | #outputs: 513 | #I make decorators! I am executed only once: when you make me create a decorator. 514 | #As a decorator maker, I return a decorator 515 | 516 | # 然后我们对这个函数进行装饰 517 | def decorated_function(): 518 | print "I am the decorated function." 519 | 520 | decorated_function = new_decorator(decorated_function) 521 | #outputs: 522 | #I am a decorator! I am executed only when you decorate a function. 523 | #As the decorator, I return the wrapped function 524 | 525 | # 我们来调用这个函数: 526 | decorated_function() 527 | #outputs: 528 | #I am the wrapper around the decorated function. I am called when you call the decorated function. 529 | #As the wrapper, I return the RESULT of the decorated function. 530 | #I am the decorated function. 531 | 532 | 这里没有惊喜。 533 | 534 | 让我们做完全相同的事情,但跳过所有讨厌的中间变量: 535 | 536 | def decorated_function(): 537 | print "I am the decorated function." 538 | decorated_function = decorator_maker()(decorated_function) 539 | #outputs: 540 | #I make decorators! I am executed only once: when you make me create a decorator. 541 | #As a decorator maker, I return a decorator 542 | #I am a decorator! I am executed only when you decorate a function. 543 | #As the decorator, I return the wrapped function. 544 | 545 | # Finally: 546 | decorated_function() 547 | #outputs: 548 | #I am the wrapper around the decorated function. I am called when you call the decorated function. 549 | #As the wrapper, I return the RESULT of the decorated function. 550 | #I am the decorated function. 551 | 552 | 让我们把它缩短: 553 | 554 | @decorator_maker() 555 | def decorated_function(): 556 | print "I am the decorated function." 557 | #outputs: 558 | #I make decorators! I am executed only once: when you make me create a decorator. 559 | #As a decorator maker, I return a decorator 560 | #I am a decorator! I am executed only when you decorate a function. 561 | #As the decorator, I return the wrapped function. 562 | 563 | #最后: 564 | decorated_function() 565 | #outputs: 566 | #I am the wrapper around the decorated function. I am called when you call the decorated function. 567 | #As the wrapper, I return the RESULT of the decorated function. 568 | #I am the decorated function. 569 | decorated_function() 570 | 571 | 嘿,你看到了吗?我们在调用函数时使用了 `@`语句。 572 | 573 | 所以,返回到带有函数的装饰器。如果我们可以使用函数来生成动态的装饰器,我们就可以将参数传递给函数,对吗? 574 | 575 | def decorator_maker_with_arguments(decorator_arg1, decorator_arg2): 576 | 577 | print "I make decorators! And I accept arguments:", decorator_arg1, decorator_arg2 578 | 579 | def my_decorator(func): 580 | # 这里的传递参数的功能是得益于闭包。 581 | # 如果你不喜欢使用闭包,你可以假定它是ok或read:http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python 582 | print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2 583 | 584 | # 不要混淆装饰器参数和函数参数! 585 | def wrapped(function_arg1, function_arg2) : 586 | print ("I am the wrapper around the decorated function.\n" 587 | "I can access all the variables\n" 588 | "\t- from the decorator: {0} {1}\n" 589 | "\t- from the function call: {2} {3}\n" 590 | "Then I can pass them to the decorated function" 591 | .format(decorator_arg1, decorator_arg2, 592 | function_arg1, function_arg2)) 593 | return func(function_arg1, function_arg2) 594 | 595 | return wrapped 596 | 597 | return my_decorator 598 | 599 | @decorator_maker_with_arguments("Leonard", "Sheldon") 600 | def decorated_function_with_arguments(function_arg1, function_arg2): 601 | print ("I am the decorated function and only knows about my arguments: {0}" 602 | " {1}".format(function_arg1, function_arg2)) 603 | 604 | decorated_function_with_arguments("Rajesh", "Howard") 605 | #outputs: 606 | #I make decorators! And I accept arguments: Leonard Sheldon 607 | #I am the decorator. Somehow you passed me arguments: Leonard Sheldon 608 | #I am the wrapper around the decorated function. 609 | #I can access all the variables 610 | # - from the decorator: Leonard Sheldon 611 | # - from the function call: Rajesh Howard 612 | #Then I can pass them to the decorated function 613 | #I am the decorated function and only knows about my arguments: Rajesh Howard 614 | 615 | 这就是带有参数的装饰器。参数可以被设置为变量: 616 | 617 | c1 = "Penny" 618 | c2 = "Leslie" 619 | 620 | @decorator_maker_with_arguments("Leonard", c1) 621 | def decorated_function_with_arguments(function_arg1, function_arg2): 622 | print ("I am the decorated function and only knows about my arguments:" 623 | " {0} {1}".format(function_arg1, function_arg2)) 624 | 625 | decorated_function_with_arguments(c2, "Howard") 626 | #outputs: 627 | #I make decorators! And I accept arguments: Leonard Penny 628 | #I am the decorator. Somehow you passed me arguments: Leonard Penny 629 | #I am the wrapper around the decorated function. 630 | #I can access all the variables 631 | # - from the decorator: Leonard Penny 632 | # - from the function call: Leslie Howard 633 | #Then I can pass them to the decorated function 634 | #I am the decorated function and only knows about my arguments: Leslie Howard 635 | 636 | 正如你可以看到的那样,你可以通过这个小把戏,把参数传递给和任何函数一样的装饰器。如果你愿意,你甚至可以使用*args 和**kwargs。但是记住,装饰器只能被调用一次,也就是当Python导入脚本的时候。在这之后,你就不能动态地设置参数。当你使用“import x”的时候,参数已经被装饰,所以你无法改变什么。 637 | 638 | 让我们实践一下:修饰装饰器 639 | 640 | 好吧,作为奖励,我会给你提供一段练习,使得任何一个装饰器接受通用的任何参数。毕竟,为了接受参数,我们用另一个函数创建了我们的装饰器。 641 | 642 | 我们包装了装饰器。 643 | 644 | 我们最近有没有看到任何其它的被包装函数? 645 | 646 | 哦,是的,装饰器! 647 | 648 | 让我们找一些乐趣,包装一下装饰器: 649 | 650 | def decorator_with_args(decorator_to_enhance): 651 | """ 652 | 这个函数应该被用作装饰器。 653 | 它必须装饰另一个被确定用作装饰器的函数。 654 | 喝一杯咖啡。 655 | 这将允许任何装饰器接受任意数量的参数, 656 | 这样你就不必每一次都要记着如何去做。 657 | """ 658 | 659 | #我们用相同的把戏来传递参数 660 | def decorator_maker(*args, **kwargs): 661 | 662 | # 我们动态地创建只接受一个函数的装饰器,但对外隐藏所传递的参数。 663 | def decorator_wrapper(func): 664 | 665 | # 我们返回到原始装饰器的结果,它毕竟只是一个普通的函数(返回到一个函数)。 666 | # 唯一的陷阱:装饰器必须有这个独特的签名,否则就无法运行: 667 | return decorator_to_enhance(func, *args, **kwargs) 668 | 669 | return decorator_wrapper 670 | 671 | return decorator_maker 672 | 673 | 它的使用方法如下: 674 | 675 | # 创建被用作装饰器的函数,并在上面贴上装饰器的标签:-) 676 | # 不要忘记“decorator(func, *args, **kwargs)” 677 | @decorator_with_args 678 | def decorated_decorator(func, *args, **kwargs): 679 | def wrapper(function_arg1, function_arg2): 680 | print "Decorated with", args, kwargs 681 | return func(function_arg1, function_arg2) 682 | return wrapper 683 | 684 | # 然后你可以根据自己的意愿,用全新的装饰器来装饰函数。 685 | 686 | @decorated_decorator(42, 404, 1024) 687 | def decorated_function(function_arg1, function_arg2): 688 | print "Hello", function_arg1, function_arg2 689 | 690 | decorated_function("Universe and", "everything") 691 | #outputs: 692 | #Decorated with (42, 404, 1024) {} 693 | #Hello Universe and everything 694 | 695 | # Whoooot! 696 | 697 | 如果你不喜欢过长的解释,参见Paolo Bergantino’s的回答(即答案1)。 698 | 699 | 我知道,你最后一次有这种感觉是在听一个人说“在理解递归之前,你必须先认识递归”的时候。但现在你掌握了装饰器,是不是感觉良好呢? 700 | 701 | **最佳实践:装饰器** 702 | 703 | Python 2.4增加了装饰器,所以要确保你的代码在大于或等于 2.4的Python版本上运行。 704 | 705 | 装饰器会减缓对函数的调用。记住这一点。 706 | 707 | 你无法撤销对函数的装饰。(有些技巧能用于创建可以撤销的装饰器,但是无人采用。)所以一旦函数被装饰,它所有的代码就都被装饰。 708 | 709 | 装饰器对函数进行包装,这使函数很难调试。(在大于或等于2.5的Python版本中有所改进;见下文。) 710 | 711 | Python 2.5开始有了functools模块。它包括函数functools.wraps()。这个函数把名称、模块和被装饰函数的函数文档字符串拷贝到包装器中。 712 | (有趣的事实:functools.wraps()是装饰器!☺) 713 | 714 | # 为了便于调试,堆栈轨迹为你打印出函数`__name__` 715 | def foo(): 716 | print "foo" 717 | 718 | print foo.__name__ 719 | #outputs: foo 720 | 721 | # 有了装饰器的它变得有些凌乱 722 | def bar(func): 723 | def wrapper(): 724 | print "bar" 725 | return func() 726 | return wrapper 727 | 728 | @bar 729 | def foo(): 730 | print "foo" 731 | 732 | print foo.__name__ 733 | #outputs: wrapper 734 | 735 | #"functools"对此有所帮助, 736 | 737 | import functools 738 | 739 | def bar(func): 740 | 741 | #我们所说的"wrapper"正在包装"func",魔力开始出现了。 742 | 743 | @functools.wraps(func) 744 | def wrapper(): 745 | print "bar" 746 | return func() 747 | return wrapper 748 | 749 | @bar 750 | def foo(): 751 | print "foo" 752 | 753 | print foo.__name__ 754 | #outputs: foo 755 | 756 | 如何让装饰器派上用场? 757 | 758 | 现在的大问题是:我可以用装饰器做什么呢? 759 | 760 | 装饰器似乎很酷很强大,但有一个实际的例子还是好的。装饰器的使用可以有1000种可能性。经典的用途是从外部静态数据连接库对函数的功能进行扩展(你不能修改它),或者用于调试(你无需修改它,因为它是暂时的)。 761 | 762 | 你可以遵循DRY (Don't Repeat Yourself)原则用装饰器来扩展几个函数,比如: 763 | 764 | def benchmark(func): 765 | """ 766 | 一个记录函数执行时间的装饰器。 767 | """ 768 | import time 769 | 770 | def wrapper(*args, **kwargs): 771 | t = time.clock() 772 | res = func(*args, **kwargs) 773 | print func.__name__, time.clock()-t 774 | return res 775 | return wrapper 776 | 777 | def logging(func): 778 | """ 779 | 一个记录脚本活动的装饰器。(它实际上只是打印它,但它可以记录!) 780 | """ 781 | def wrapper(*args, **kwargs): 782 | res = func(*args, **kwargs) 783 | print func.__name__, args, kwargs 784 | return res 785 | return wrapper 786 | 787 | 788 | def counter(func): 789 | """ 790 | 一个统计和打印函数运行次数的装饰器 791 | """ 792 | def wrapper(*args, **kwargs): 793 | wrapper.count = wrapper.count + 1 794 | res = func(*args, **kwargs) 795 | print "{0} has been used: {1}x".format(func.__name__, wrapper.count) 796 | return res 797 | wrapper.count = 0 798 | return wrapper 799 | 800 | @counter 801 | @benchmark 802 | @logging 803 | def reverse_string(string): 804 | return str(reversed(string)) 805 | 806 | print reverse_string("Able was I ere I saw Elba") 807 | print reverse_string("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!") 808 | 809 | #outputs: 810 | #reverse_string ('Able was I ere I saw Elba',) {} 811 | #wrapper 0.0 812 | #wrapper has been used: 1x 813 | #ablE was I ere I saw elbA 814 | #reverse_string ('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!',) {} 815 | #wrapper 0.0 816 | #wrapper has been used: 2x 817 | #!amanaP :lanac a ,noep a ,stah eros ,raj a ,hsac ,oloR a ,tur a ,mapS ,snip ,eperc a ,)lemac a ro( niaga gab ananab a ,gat a ,nat a ,gab ananab a ,gag a ,inoracam ,elacrep ,epins ,spam ,arutaroloc a ,shajar ,soreh ,atsap ,eonac a ,nalp a ,nam A 818 | 819 | 当然,装修器的好处是,你几乎可以在任何内容上立即使用它们,而无需重写。我说过DRY(Don't Repeat Yourself原则,写代码的时候尽量避免重复的实现)。 820 | 821 | @counter 822 | @benchmark 823 | @logging 824 | def get_random_futurama_quote(): 825 | from urllib import urlopen 826 | result = urlopen("http://subfusion.net/cgi-bin/quote.pl?quote=futurama").read() 827 | try: 828 | value = result.split("


")[1].split("


")[0] 829 | return value.strip() 830 | except: 831 | return "No, I'm ... doesn't!" 832 | 833 | print get_random_futurama_quote() 834 | print get_random_futurama_quote() 835 | 836 | #outputs: 837 | #get_random_futurama_quote () {} 838 | #wrapper 0.02 839 | #wrapper has been used: 1x 840 | #The laws of science be a harsh mistress. 841 | #get_random_futurama_quote () {} 842 | #wrapper 0.01 843 | #wrapper has been used: 2x 844 | #Curse you, merciful Poseidon! 845 | 846 | Python本身提供了好几种装饰器:property、staticmethod等。 847 | 848 | - Django使用装饰器来管理高速缓存和视图的权限。 849 | - Twisted来假冒内联异步函数的调用。 850 | 851 | 这真是一个大型游乐场。 852 | -------------------------------------------------------------------------------- /304.md: -------------------------------------------------------------------------------- 1 | #`if __name__ == "__main__"`是做什么用的? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/419163/what-does-if-name-main-do 4 | 5 | ##问题: 6 | 7 | `if __name__ == "__main__"`是做什么用的? 8 | 9 | # Threading example 10 | import time, thread 11 | 12 | def myfunction(string, sleeptime, lock, *args): 13 | while 1: 14 | lock.acquire() 15 | time.sleep(sleeptime) 16 | lock.release() 17 | time.sleep(sleeptime) 18 | if __name__ == "__main__": 19 | lock = thread.allocate_lock() 20 | thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) 21 | thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) 22 | 23 | ##答案: 24 | 25 | 当Python解释器读取源文件时,它执行在Python中所能找到的所有代码。在执行代码之前,它将定义一些特殊变量。例如,如果Python解释器把这个模块(源文件)作为主程序来运行,它就把特殊变量`__name__`的值设置为`__main__`。如果这个文件从另一个模块被引入,`__name__`将被设置为模块的名字。 26 | 27 | 至于你的脚本,让我们假设它正在执行主函数,例如,你在命令行键入下面的内容 28 | 29 | python threading_example.py 30 | 31 | 设置了特定的变量后,Python将执行`import`语句并加载这些模块。然后,执行`def`语句块,创建一个函数对象并实现`myfunction`这个名称指向函数对象。接着,它会读取if语句,并确保`__name__`等于`__main__`,之后,它将执行所显示的语句块。 32 | 33 | 这样做的原因之一是:有时候你把一个模块(.py文件)写在可以直接被执行的地方。另外,这个模块也可以被引入,并在另一个模块中被使用。经过`__main__`检查,你可以让代码只有在你想把该模块作为程序来运行的时候才被执行,而不是在有人只想引用模块并调用你的函数时被执行。 34 | 35 | 你可以访问这个页面来了解一些额外的细节,[this page](http://ibiblio.org/g2swap/byteofpython/read/module-name.html) 36 | 37 | 38 | ------- 39 | 40 | 打赏帐号:qiwsir@126.com(支付宝) 41 | -------------------------------------------------------------------------------- /305.md: -------------------------------------------------------------------------------- 1 | #@staticmethod(静态方法)和@classmethod(类方法)有什么区别? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python 4 | 5 | ##问题: 6 | 7 | 用[@staticmethod](http://docs.python.org/2/library/functions.html#staticmethod)装饰的函数和用[ @classmethod](http://docs.python.org/2/library/functions.html#classmethod)装饰的函数有什么区别? 8 | 9 | ##答案: 10 | 11 | 也许一些代码示例会有所帮助。注意`foo`、 `class_foo` 和 `static_foo` 在调用方面的差异: 12 | 13 | class A(object): 14 | def foo(self,x): 15 | print "executing foo(%s,%s)"%(self,x) 16 | 17 | @classmethod 18 | def class_foo(cls,x): 19 | print "executing class_foo(%s,%s)"%(cls,x) 20 | 21 | @staticmethod 22 | def static_foo(x): 23 | print "executing static_foo(%s)"%x 24 | 25 | a=A() 26 | 27 | 下面是在实例中来调用方法的一种常用方式。实例`a`,被当作第一个参数隐式传递。 28 | 29 | a.foo(1) 30 | # executing foo(<__main__.A object at 0xb7dbef0c>,1) 31 | 32 | 装饰类方法(classmethods),实例的类是作为第一个参数隐式传递,从而代替了`self`。 33 | 34 | a.class_foo(1) 35 | # executing class_foo(,1) 36 | 37 | 你还可以使用类来调用`class_foo`。事实上,如果你把某个东西定义为classmethod,可能是因为你打算从类而不是从类的实例中调用它。`A.foo(1)`可能会引发TypeError,但`A.class_foo(1)`刚刚好: 38 | 39 | A.class_foo(1) 40 | # executing class_foo(,1) 41 | 42 | 人们已经发现类方法的一种用途是[创建可继承的替代性构造函数(inheritable alternative constructors)](http://stackoverflow.com/a/1950927/190597)。 43 | 44 | 在静态方法中,self(对象实例)和cls(类)都不能作为第一个参数来隐式传递。它们的功能就像普通函数一样,只不过你可以从实例或类来调用它们: 45 | 46 | a.static_foo(1) 47 | # executing static_foo(1) 48 | 49 | A.static_foo('hi') 50 | # executing static_foo(hi) 51 | 52 | Staticmethods用来对函数进行分组,这些函数和某个类有着逻辑关联。 53 | 54 | `foo`只是一个函数,但是当你调用`a.foo`时,你得到的不只是函数本身,你还会得到该函数的一个“局部应用”的版本,并且对象实例被绑定为该函数的第一个参数。`foo`有2个参数,而`a.foo`只有1个参数。 55 | 56 | 下面这个术语“绑定”的意思是说:`a`被绑定到`foo`。 57 | 58 | print(a.foo) 59 | # > 60 | 61 | 在`a.class_foo`中,被绑定到`class_foo`的不是`a`,而是`A`这个类。 62 | 63 | print(a.class_foo) 64 | # > 65 | 66 | 尽管这里的staticmethod是一个方法,a.static_foo也只是返回函数,并且这个函数没有绑定的参数。static_foo 有1个参数,a.static_foo也有1个参数。 67 | 68 | print(a.static_foo) 69 | # 70 | 71 | 当然,当你用A这个类来调用static_foo的时候,会出现同样的情况。 72 | 73 | print(A.static_foo) 74 | # 75 | 76 | 【编者注:另外对静态方法和类方法的比较,可以参考:[《零基础学Python(第二版)之类(5)部分》](https://github.com/qiwsir/StarterLearningPython/blob/master/210.md)】 -------------------------------------------------------------------------------- /306.md: -------------------------------------------------------------------------------- 1 | #如何通过参数来传递一个变量? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference 4 | 5 | ##问题: 6 | 7 | Python文档似乎没有明确指出参数是否通过引用或通过值进行传递,而且下面的代码产生了不变的值“Original” 8 | 9 | class PassByReference: 10 | def __init__(self): 11 | self.variable = 'Original' 12 | self.Change(self.variable) 13 | print self.variable 14 | 15 | def Change(self, var): 16 | var = 'Changed' 17 | 18 | 我怎样通过实际的参数来传递变量? 19 | 20 | ##答案: 21 | 22 | 参数是[通过引用来传递的(passed by assignment)](http://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference)。其原理是双重的: 23 | 24 | 1. 被传入的参数实际上是对象的引用(但对象的引用是按值传递的)。 25 | 2. 一些数据类型是可变的,但其他数据类型是不变的。 26 | 27 | 因此: 28 | 29 | - 如果你把一个可变对象传递到一个方法,该方法参数引用了对这个可变对象,你可以随意改变它,但如果你重新绑定该方法中的参数,外部范围将无从知晓。在你重新绑定之后,外部引用仍然指向原来的对象。 30 | - 如果你把一个不可变的对象传递到一个方法,你仍然无法绑定外部引用,你甚至无法改变这个对象。 31 | 32 | 为了更清楚地了解这个问题,我们来看一些例子。 33 | 34 | ###列表 - 可变类型 35 | 36 | 让我们尝试修改被传递到方法的列表: 37 | 38 | def try_to_change_list_contents(the_list): 39 | print 'got', the_list 40 | the_list.append('four') 41 | print 'changed to', the_list 42 | 43 | outer_list = ['one', 'two', 'three'] 44 | 45 | print 'before, outer_list =', outer_list 46 | try_to_change_list_contents(outer_list) 47 | print 'after, outer_list =', outer_list 48 | 49 | 输出: 50 | 51 | before, outer_list = ['one', 'two', 'three'] 52 | got ['one', 'two', 'three'] 53 | changed to ['one', 'two', 'three', 'four'] 54 | after, outer_list = ['one', 'two', 'three', 'four'] 55 | 56 | 由于被传入的参数是outer_list的一个引用,而不是它的一个副本,我们可以用改变列表的方法来改变它,让这些变化在外部范围也能体现出来。 57 | 58 | 现在让我们看看当我们试图改变通过参数传入的引用时会发生什么情况: 59 | 60 | def try_to_change_list_reference(the_list): 61 | print 'got', the_list 62 | the_list = ['and', 'we', 'can', 'not', 'lie'] 63 | print 'set to', the_list 64 | 65 | outer_list = ['we', 'like', 'proper', 'English'] 66 | 67 | print 'before, outer_list =', outer_list 68 | try_to_change_list_reference(outer_list) 69 | print 'after, outer_list =', outer_list 70 | 71 | 输出: 72 | 73 | before, outer_list = ['we', 'like', 'proper', 'English'] 74 | got ['we', 'like', 'proper', 'English'] 75 | set to ['and', 'we', 'can', 'not', 'lie'] 76 | after, outer_list = ['we', 'like', 'proper', 'English'] 77 | 78 | 由于the_list参数是按值传递的,给它分配一个新的列表丝毫不会影响到方法之外的代码。the_list是outer_list参数的一个副本,the_list指向一个新的列表,但是没有办法改变outer_list的指向。 79 | 80 | ###字符串 - 一个不可改变的类型 81 | 82 | 字符串是不可改变的,所以我们无法改变字符串的内容。 83 | 84 | 现在,让我们试着改变参数。 85 | 86 | def try_to_change_string_reference(the_string): 87 | print 'got', the_string 88 | the_string = 'In a kingdom by the sea' 89 | print 'set to', the_string 90 | 91 | outer_string = 'It was many and many a year ago' 92 | 93 | print 'before, outer_string =', outer_string 94 | try_to_change_string_reference(outer_string) 95 | print 'after, outer_string =', outer_string 96 | 97 | 输出 98 | 99 | before, outer_string = It was many and many a year ago 100 | got It was many and many a year ago 101 | set to In a kingdom by the sea 102 | after, outer_string = It was many and many a year ago 103 | 104 | 此外,由于the_string参数是按值传递的,给它分配一个新的字符串丝毫不会影响到方法之外的代码。the_string是outer_string参数的一个副本,the_string指向一个新的字符串,但是没有办法改变outer_string的指向。 105 | 106 | 我希望上述内容对弄清这个问题有所帮助。 107 | 108 | 注:人们已经注意到,上述内容并没有回答@David最初提出的这个问题,“我怎样通过实际的参数来传递变量?”让我们着手解决这个问题。 109 | 110 | ###我们怎样解决这个问题? 111 | 112 | 正如@Andrea的回答所显示的:你可以返回到新的值。传入方式并没有改变,但你可以获取你想要取消的信息: 113 | 114 | def return_a_whole_new_string(the_string): 115 | new_string = something_to_do_with_the_old_string(the_string) 116 | return new_string 117 | 118 | # then you could call it like 119 | my_string = return_a_whole_new_string(my_string) 120 | 121 | 如果你真的想避免使用返回值,你可以创建一个类来保留你的值,并把它传递到函数,或者使用一个现有的类,如列表: 122 | 123 | def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change): 124 | new_string = something_to_do_with_the_old_string(stuff_to_change[0]) 125 | stuff_to_change[0] = new_string 126 | 127 | # then you could call it like 128 | wrapper = [my_string] 129 | use_a_wrapper_to_simulate_pass_by_reference(wrapper) 130 | 131 | do_something_with(wrapper[0]) 132 | 133 | 虽然这样做似乎有点麻烦。 134 | -------------------------------------------------------------------------------- /307.md: -------------------------------------------------------------------------------- 1 | #Python中的 `__str__`和`__repr__`之间的区别 2 | 3 | 原问题地址:http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python 4 | 5 | ##问题: 6 | 7 | Python中的`__str__`和`__repr__`有什么区别呢? 8 | 9 | ##回答: 10 | 11 | Alex总结得很好,但是简洁得出乎意料。 12 | 13 | 首先,让我重申Alex的主要观点: 14 | 15 | - 默认实现是没有用的(很难想象一个有用的默认实现,但事实的确如此) 16 | - `__repr__`目标是准确性 17 | - `__str__`目标是可读性 18 | - 容器的`__str__`使用容器所包含对象的`__repr__` 19 | 20 | ###默认实现是没有用的 21 | 22 | 多半是惊喜,因为Python的默认值往往是相当有用的。然而,在这种情况下,有一个像这样的针对`__repr__`的默认实现 23 | 24 | return "%s(%r)" % (self.__class__, self.__dict__) 25 | 26 | 会有很大的危险(例如,如果对象之间相互引用,太容易陷入无限递归)。所以Python避开了这一点。注意,有一个默认实现:如果`__repr__`被定义,并且`__str__`没有被定义,对象的工作原理就好像`__str__=__repr__`。 27 | 28 | 简单来说,这意味着:几乎你所实现的每一个对象都应该有一个`__repr__`函数来用于理解这个对象。实现`__str__`是可选的:如果你需要 “优质打印”功能(例如,用于报表)【译者注:“优质打印”,意思是要得到非常友好的输出效果】,你就要实现`__str__`。 29 | 30 | ### `__repr__`的目标在于准确性 31 | 32 | 坦率地说,我不相信调试器。我真的不知道如何使用,而且从来没有认真地使用过任何调试器。此外,我认为调试器的一个大缺点在于它的本质——很久以前,我在进行调试过程中发现了太多的问题距真正的错误差距很大。这就意味着,我对日志要有着宗教般的热情。日志记录是任何一个像样的容灾备份服务器系统的生命线。用Python记录日志很容易:也许对于某些具体项目的封装,你所需要的只是如下操作: 33 | log(INFO, "I am in the weird function and a is", a, "and b is", b, "but I got a null C — using default", default_c) 34 | 35 | 但是你必须做到最后一步——确保你所实现的每个对象都有一个可用的repr函数,那样的代码才可以正常运行。下面解释为什么要使用“eval”:如果你有足够的信息,能实现 `eval(repr(c))==c`,这就意味着你所掌握的信息足以让你了解c。如果这样做很容易,做下去,至少用一个模糊的方式来做。如果不容易,无论如何也要确保你获取了关于c的足够的信息。我通常使用类似于eval的格式:`"MyClass(this=%r,that=%r)" % (self.this,self.that)`。这并不意味着你可以真正构建MyClass或者那些正确的构造函数参数——但它对于表达“这是你需要了解的关于这个实例所有信息”是一种有用的形式。 36 | 37 | 注意:我在上面使用的是%r,而不是%s。在`__repr__`实现中,你总是用`repr()` [或相同的格式化字符%r],否则无法达成repr的目标。你要能够区分`MyClass(3)`和`MyClass("3")`。 38 | 39 | ###`__str__`的目标在于可读性 40 | 41 | 特别说明,它不在意准确性——注意`str(3)==str("3")`。同样地,如果你要实现IP地址抽象,有个类似于192.168.1.1的str就好。当实现一个日期/时间抽象时,str可以是“2010/4/12 15:35:22”等。目标在于:让用户而不是程序员更容易阅读。删掉无用的数字,伪装成其它的类——只要它具有可读性,这就是一种改进。 42 | 43 | ###容器的`__str__`使用了所包含对象的`__repr__` 44 | 45 | 这似乎令人惊讶,不是吗?这的确有点意外,但可读性如何? 46 | 47 | [moshe is, 3, hello world, this is a list, oh I don't know, containing just 4 elements] 48 | 49 | 可读性不很强。具体而言,容器中字符串的表示形式太容易受干扰。面对歧义,记住,Python拒绝猜测。如果你在打印一个列表的时候你想要实现上述功能,只需要 50 | 51 | print "["+", ".join(l)+"]" 52 | 53 | (或许你也可以弄清楚字典的相关方法。) 54 | 55 | ###总结 56 | 57 | 对于你所实现的任何的类都可以使用`__repr__`。这应该成为你的习惯。如果你认为实现`__str__`导致了歧义,但较少有错误,并有更好的可读性,则可以使用`__str__`。 -------------------------------------------------------------------------------- /308.md: -------------------------------------------------------------------------------- 1 | #如何使用 ' super ' 2 | 3 | 原问题地址:http://stackoverflow.com/questions/222877/how-to-use-super-in-python 4 | 5 | ##问题: 6 | 7 | 有人能给我解释下面两组代码的区别吗? 8 | 9 | class Child(SomeBaseClass): 10 | def __init__(self): 11 | super(Child, self).__init__() 12 | 13 | 和这个: 14 | 15 | class Child(SomeBaseClass): 16 | def __init__(self): 17 | SomeBaseClass.__init__(self) 18 | 19 | 我在类里面看到过很多关于super的应用,这些类都只有单一继承。我能明白为什么你会在多重继承中使用它,但我不清楚在这种情况下使用它有什么优势。 20 | 21 | ##回答 1: 22 | 23 | 在单一继承中使用`super()`的好处微乎其微。主要的好处是:你不需要把基类的名称硬编码到每一个使用父类方法的方法中。 24 | 25 | 然而,使用不带有`super()`的多重继承几乎是不可能的。包括常见的如混入类【译者注:关于mixin(混入类),推荐阅读:[设计模式 Mixin (混入类)](http://www.cnblogs.com/youxin/p/3623329.html)】、接口、抽象类,等等。这样的拓展了你编码。如果有人将来想创建一个类,让这个类从子类扩展到混入类,他们的代码将无法正常运行。 26 | 27 | ##回答 2: 28 | 29 | ###间接的向前兼容性 30 | 31 | super的应用给你带来了什么?对于单一继承,上述内容实际上是从静态分析的角度来看问题的。然而,super使你的代码具有间接的向前兼容性。 32 | 33 | 向前兼容性对经验丰富的开发人员非常重要。你希望在你对代码做出修改后,能够以最低限度的代价继续工作。当你查看修订记录时,你想精确地看到修改的时间和内容。 34 | 35 | 你可以从单一继承开始,但是如果你决定添加另一个基类,你只需要改变基类那行。特别是在Python 2中,恰当地获取super的参数和正确的方法参数是很困难的。如果你知道你在正确使用带有单一继承的super,调试的进展就不那么困难。 36 | 37 | ###依赖注入 38 | 39 | 其他人可以使用你的代码,并向你的方法解析中注入父类方法: 40 | 41 | class SomeBaseClass(object): 42 | def __init__(self): 43 | print('SomeBaseClass.__init__(self) called') 44 | 45 | class Child(SomeBaseClass): 46 | def __init__(self): 47 | print('Child.__init__(self) called') 48 | SomeBaseClass.__init__(self) 49 | 50 | class SuperChild(SomeBaseClass): 51 | def __init__(self): 52 | print('SuperChild.__init__(self) called') 53 | super(SuperChild, self).__init__() 54 | 55 | 例如,你把另一个类添加到你的对象,并且想要在Foo和Bar之间注入类(用于测试或其他原因): 56 | 57 | class InjectMe(SomeBaseClass): 58 | def __init__(self): 59 | print('InjectMe.__init__(self) called') 60 | super(InjectMe, self).__init__() 61 | 62 | class UnsuperInjector(Child, InjectMe): pass 63 | 64 | class SuperInjector(SuperChild, InjectMe): pass 65 | 66 | 使用不带有super的子类没能成功地注入依赖,因为你试图通过硬编码方法调用正在使用的子类本身: 67 | 68 | >>> o = UnsuperInjector() 69 | Child.__init__(self) called 70 | SomeBaseClass.__init__(self) called 71 | 72 | 然而,如果你的类所包含的子类使用了super,这个类就可以正确地注入依赖: 73 | 74 | >>> o2 = SuperInjector() 75 | SuperChild.__init__(self) called 76 | InjectMe.__init__(self) called 77 | SomeBaseClass.__init__(self) called 78 | 79 | 不使用super有可能给你的代码用户带来不必要的限制。 -------------------------------------------------------------------------------- /309.md: -------------------------------------------------------------------------------- 1 | #Python中的静态方法? 2 | 3 | 原问题地址:http://stackoverflow.com/questions/735975/static-methods-in-python 4 | 5 | ##问题: 6 | 7 | 在Python中有没有可能调用静态方法而无需对类进行初始化,如: 8 | 9 | ClassName.StaticMethod ( ) 10 | 11 | ##回答: 12 | 13 | 是的,使用staticmethod装饰器 14 | 15 | class MyClass(object): 16 | @staticmethod 17 | def the_static_method(x): 18 | print x 19 | 20 | MyClass.the_static_method(2) # outputs 2 21 | 22 | 请注意,某些代码可能使用老方法来定义静态法,把静态法作为函数而不是装饰器来应用。如果你不得不支持Python的老版本(2.2和2.3)的时候,才会这样用。 23 | 24 | class MyClass(object): 25 | def the_static_method(x): 26 | print x 27 | the_static_method = staticmethod(the_static_method) 28 | 29 | MyClass.the_static_method(2) # outputs 2 30 | 31 | 这和第一个例子完全相同(使用`@staticmethod`),只是没有采用好用的装饰器语法。 32 | 33 | 最后,有节制地使用`staticmethod()`!在Python中只有极少数情况下才有必要使用静态方法。我见过对于`staticmethod()`的多次使用,而这些时候,独特的“顶级”函数往往表达得更清晰。 34 | -------------------------------------------------------------------------------- /401.md: -------------------------------------------------------------------------------- 1 | #在Python中调用外部命令 2 | 3 | 原问题地址:http://stackoverflow.com/questions/89228/calling-an-external-command-in-python 4 | 5 | ##问题: 6 | 7 | 我如何在Python脚本内部调用外部命令(就好像我在Unix shell命令行或者在Windows命令提示符中键入外部命令那样)? 8 | 9 | ##答案 1: 10 | 11 | 参看标准函数库中的[subprocess module](https://docs.python.org/2/library/subprocess.html): 12 | 13 | from subprocess import call 14 | call(["ls", "-l"]) 15 | 16 | Subprocess模块相对于`os.system`的优势在于它的灵活性更强(你可以获得标准输出、标准错误、“真实”的状态码、更好的错误处理,等等)。我认为os.system已过时或即将过时(参考阅读:[https://docs.python.org/2/library/subprocess.html#replacing-older-functions-with-the-subprocess-module](https://docs.python.org/2/library/subprocess.html#replacing-older-functions-with-the-subprocess-module)) 17 | 18 | 然而,os.system对于快速上手的脚本或一次性脚本是够用的。 19 | 20 | ##答案 2: 21 | 22 | 这里总结了调用外部程序的方法和每个方法的优缺点: 23 | 24 | 1、`os.system("some_command with args")`把命令和参数发送到shell。这是很好的,因为这种方式实际上可以使你同时运行多个命令、设置管道和输入/输出重定向。例如, 25 | 26 | os.system("some_command < input_file | another_command > output_file") 27 | 28 | 然而,虽然这样做很方便,你却必须处理转义shell中的字符,如:空格等。另一方面,这也使得你所运行的命令仅仅是shell命令,实际上并不是外部程序。 29 | [阅读材料](https://docs.python.org/2/library/os.html#os.system) 30 | 31 | 2、`stream = os.popen("some_command with args")`也可以实现`os.system`的功能,只不过它给了你一个类似文件的对象,有了这个对象,你就可以为那个进程使用标准输入/输出。对于os.popen还有3种其他的变式,它们在处理i/o的方式上略有不同。如果你把每个命令都当作字符串来传递,那么你的命令就被传递到shell;如果你把这些命令作为列表来传递,你就不必担心转义的问题。[阅读材料](https://docs.python.org/2/library/os.html#os.popen) 32 | 33 | 3、`subprocess`模块的`Popen`类。`Popen`旨在替代`os.popen`,但它本身的综合性使它有点复杂。例如,你会使用 34 | 35 | print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read() 36 | 37 | 而不是 38 | 39 | print os.popen("echo Hello World").read() 40 | 41 | 这些选择都是在一个统一的类中而不是在4个不同的popen函数中,这总归是好的。[阅读材料](https://docs.python.org/2/library/subprocess.html#popen-constructor) 42 | 43 | 4、从subprocess模块中调用函数。这基本上就像Popen类一样,采用的都是相同的参数,但它只是等待命令完成并返回代码。例如: 44 | 45 | return_code = subprocess.call("echo Hello World", shell=True) 46 | 47 | [阅读材料](https://docs.python.org/2/library/subprocess.html#subprocess.call) 48 | 49 | 5、如果你使用的是Python 3.5或更高版本,你可以使用新的[subprocess.run功能](https://docs.python.org/3.5/library/subprocess.html#subprocess.run)。`subprocess.run`和以上的方法很像,但更灵活,而且当命令执行完毕时,返回[CompletedProcess对象](https://docs.python.org/3.5/library/subprocess.html#subprocess.CompletedProcess)。 50 | 51 | 6、os模块具有C程序中的所有的`fork/exec/spawn`功能,但我不建议直接使用它们。 52 | 53 | 也许你应该使用的是subprocess模块。 54 | 55 | 最后,请注意:在所有的方法中,你把最终命令作为一个字符串发送到shell来执行的时候,你就要负责对它进行转义。如果你所发送的任何部分的字符串不能完全被信任,就会有严重的安全隐患。(例如,如果用户正在确认执行某一部分或任何部分的字指令)。如果你不确定,只使用这些带有常量的方法。为了对这些隐患稍作了解,考虑一下这个代码 56 | 57 | print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read() 58 | 59 | 想象一下,用户执行“my mama didnt love me && rm -rf /”。 60 | 61 | ------- 62 | 63 | 打赏帐号:qiwsir@126.com(支付宝),qiwsir(微信号) 64 | -------------------------------------------------------------------------------- /402.md: -------------------------------------------------------------------------------- 1 | #在Python中检查目录是否存在,如果有必要就创建一个目录 2 | 3 | 原问题地址:http://stackoverflow.com/questions/273192/in-python-check-if-a-directory-exists-and-create-it-if-necessary 4 | 5 | ##问题: 6 | 7 | 把文件写入某个目录之前,想要检查这个目录是否存在,实现这个目的的最优雅的方式是什么?如果这个目录不存在,用Python创建此目录的最优雅的方式是什么?这是我的尝试: 8 | 9 | filename = "/my/directory/filename.txt" 10 | dir = os.path.dirname(filename) 11 | 12 | try: 13 | os.stat(dir) 14 | except: 15 | os.mkdir(dir) 16 | 17 | f = file(filename) 18 | 19 | 不知怎的,我漏掉了`os.path.exists`(感谢kanja, Blair, and Douglas)。这是我现在得出的代码: 20 | 21 | def ensure_dir(f): 22 | d = os.path.dirname(f) 23 | if not os.path.exists(d): 24 | os.makedirs(d) 25 | 26 | 是否有一个“open”指令,使得这项功能自动执行? 27 | 28 | ##答案: 29 | 30 | 我看到了两个回答,它们各有可取之处,也各有一个小的缺陷,所以我给出我的回答: 31 | 尝试`os.path.exists`,并考虑把`os.makedirs`用于创建目录。 32 | 33 | if not os.path.exists(directory): 34 | os.makedirs(directory) 35 | 36 | 正如在注解和其他地方所指出的那样,这里有一个竞态条件:如果目录创建于调用`os.path.exists`和`os.makedirs`之时,`os.makedirs`将以OSError的形式宣告失败。不幸的是,重写OSError和继续执行皆非万无一失。由于权限不足、磁盘已满等其他因素,`os.makedirs`将忽略某项失败而创建该目录。 37 | 38 | 有一种选择是阻止OSError并检查错误,如果你熟悉情况(在我的操作系统中,13似乎表明权限被拒绝,17表明文件存在。目前尚不清楚,这是否更适合远程便携式操作,但[Is there a cross-platform way of getting information from Python’s OSError](http://stackoverflow.com/questions/273698/is-there-a-cross-platform-way-of-getting-information-from-pythons-oserror))对此进行了探究。或者,可能还有第二个`os.path.exists`,但假设在初次检测后由另一个途经创建了目录,然后把目录移到二次检测之前,我们仍然有可能被愚弄。 39 | 40 | 根据应用程序的不同,并行操作的危险可能比其他因素所构成的危险更多或更少,例如文件权限。在选择实施前,开发人员必须对特定的应用程序和其预期的环境有更多的了解。 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 如果你是一名自诩为程序员的,那么,就必须知道stackoverflow.com这个网站。因为它是一个非常好的技术问答网站,里面不仅有高手,更重要的是有对问题进行详细耐心解答的高手。 2 | 3 | 这里我抽空翻译了一些典型的问答,当然,只能翻译Python语言方面的,其它语言,唯恐因知之甚少而漏洞百出,即便是Python,也会因为才疏学浅,在翻译过程中感到惶恐。所以,读者如果看到错误之处,请不吝赐教。 4 | 5 | 欢迎访问:[www.itdiffer.com](http://www.itdiffer.com),加入学习Python的群组。 6 | 7 | #目录 8 | 9 | ##基本对象和语句 10 | 11 | - [Python是否有三元条件运算符](./101.md) 12 | - [如何把两个Python字典用一个表达式合并](./102.md) 13 | - [对Python字典按值排序](./103.md) 14 | - [append和extend的区别](./104.md) 15 | - [获得Python的循环索引](./105.md) 16 | - [判断一个字符串是否含子串的方法](./106.md) 17 | - [怎样在Python中实现Enum(枚举)的功能](./107.md) 18 | - [将多行的异常变成一行](./108.md) 19 | - [解释Python的切片法](./109.md) 20 | - [如何在Python中获取当前时间](./110.md) 21 | - [查看某个给定的键是否已经在字典中](./111.md) 22 | - [如何删除Python中的换行符?](./112.md) 23 | - [如何将Python列表均匀划分?](./113.md) 24 | - [join函数为什么是string.join(list)而不是list.join(string)](./114.md) 25 | - [我如何在Python中检查一个字符串否可转化为数字?](./115.md) 26 | 27 | ##文件 28 | 29 | - [如何使用Python来检查文件是否存在](./201.md) 30 | - [如何在Python中列出目录下的所有文件](./202.md) 31 | 32 | ##函数和类 33 | 34 | - [Python中yield关键词的作用是什么](./301.md) 35 | - [Python中的元类是什么](./302.md) 36 | - [怎样在Python中创建函数装饰器链](./303.md) 37 | - [`if __name__ == "__main__"`是做什么用的](./304.md) 38 | - [@staticmethod(静态方法)和@classmethod(类方法)的区别](./305.md) 39 | - [如何通过参数来传递一个变量?](./306.md) 40 | - [Python中的 `__str__`和`__repr__`之间的区别](./307.md) 41 | - [如何使用 ' super '](./308.md) 42 | - [Python中的静态方法?](./309.md) 43 | 44 | ##系统 45 | 46 | - [在Python中调用外部命令](./401.md) 47 | - [检查目录是否存在,如果有必要就创建一个目录](./402.md) 48 | 49 | ##网络 50 | --------------------------------------------------------------------------------