python内置方法、模块讲解(二十四)

  • 2016-05-29 14:54:39
  • 1082
  • 0

六十六、repr方法

1、定义:

repr(...)
    repr(object) -> string

    Return the canonical string representation of the object.
    For most object types, eval(repr(object)) == object.

2、解释:返回一个对象的规范的string表现形式,对于大多数对象类型满足以下等式:eval(repr(object)) == object.

3、举例:

>>> repr(123)
'123'
>>> repr("abc")
"'abc'"
>>> repr(dict(a=12, b="aaa", c=dict(d='dd')))
"{'a': 12, 'c': {'d': 'dd'}, 'b': 'aaa'}"
>>> _dict = repr(dict(a=12, b="aaa", c=dict(d='dd')))
>>> eval(_dict)
{'a': 12, 'c': {'d': 'dd'}, 'b': 'aaa'}

六十七、reversed类

(以下省略)

阅读更多

python内置方法、模块讲解(二十三)

  • 2016-05-29 12:37:40
  • 1106
  • 0

六十四、reduce方法

1、定义:

reduce(...)
    reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

2、解释:从左到右, 累计将一个序列的所有元素以参数的形式传入到一个需要接受两个参数的方法中, 最后将这个序列逐级递减成一个值。若initial变量存在时, 则initial变量作为第一个参数加入到计算当中。

3、举例:

>>> reduce(lambda x,y: x*y, range(1,6),10)
1200
>>> reduce(lambda x,y: x*y, range(1,6))
120
>>> reduce(lambda x,y: x*y, [], 10)
10
六十五、reload方法
1、定义:
reload(...)
    reload(module) -> module

    Reload the module.  The module must have been successfully imported before.
2、解释:很简单, reload一个之前已经导入过的模块
3、举例:
>>> import sys
>>> sys.setdefaultencoding('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'setdefaultencoding'
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('utf8')
注:setdefaultencoding函数在被系统调用后被删除了,所以通过import引用进来时其实已经没有了,所以必须reload一次sys模块,这样setdefaultencoding才会为可用,才能在代码里修改解释器当前的字符编码。

阅读更多

python内置方法、模块讲解(二十二)

  • 2016-05-23 20:47:04
  • 1187
  • 0

六十、print方法

此方法不做多讲解,python的打印函数

六十一、property类

(以下省略)

阅读更多