$ ls ~yifei/notes/

Python 的内置类型和函数

Posted on:

Last modified:

内置类型

Python 的内置类型按照类来分,包括了 numerics, sequences, mappings, files, classes, instances 和 exceptions。对用户自定义类型的实例,如果__nonzero__或者__len__返回是 0 或 False 会被认为是假。

注意浅拷贝

>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

字典的一些方法

keys()/values()
iterkeys()/itervalues()
items()/iteritems()
update()
get(key, default)

文件的方法

read/readline/readlines
write/writelines

字符串方法

str.capitalize()     首字母大写
center/ljust/rjust(width, filled_char)     扩充并使得原字符串居中
decode(codecsm, how_to_handle_erroe)     throws UnicodeError
encode(codecs, how_to_handle_error)     throws UnicodeError
startswith(string or tuple)
endswith(seq, start, end)
find(seq, start, end)
isalnum/isalpha/isdigit/islower/isupper/isspace
lower()/upper()/title()
strip/lstrip/rstrip(chars)
partition(seq)     返回一个三元组前半部分,seq,后半部分
replace(old, new, count)
split(seq, count)
splitlines(keepends)
zfill(width)     左边填零

内置函数

函数式编程

all
any
callable
filter
iter
map
next
reduce(fn, iter, init)
reload

操作属性的函数

delattr
dir    return a object"s attributes
getattr(object, name, default)    when default supplied, no exception thrown
hasattr
globals
locals

数学函数

compile
complex
bin    Convert an integer number to a binary string
abs
divmod
enumerate
eval
execfile
file
hex
max/min
oct
pow

构造函数

frozenset
bool
dict
float    note float("NaN"), float("-inf")
int(x, base=10)
list
long
object
  • bytearray 可以认为是一个可变的 string
  • frozenset 是一个 immutable, hashable 的 set

其他函数

format
enumerate
id
input/raw_inoput
isinstance(object, class/class_tuple)
insubclass(class, class)
len
open
print
range/xrange(start, stop, step)

do not subclass built-in classes in python

In short, they will not behave what you think they will. You may think dict.get is implemented like:

def get(self, key, default=None):
    try:
        return self[key]
    except KeyError:
        return default

However, dict.get do not call __getitem__, and they are implemented in c separately, and do not call each other.

So, when you implement __geitem__, get is not automatically altered, which is very dangerous.

What you need do is, subclassing collections.abc.Mapping

References

  1. http://www.kr41.net/2016/03-23-dont_inherit_python_builtin_dict_type.html

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.