Python内置函数详解

abs(x)

abs函数用来返回参数的绝对值

1
2
>>> abs(-59)
59

all(iterable)

all函数接收一个可迭代的对象作为参数,所有元素均为真则返回真

1
2
3
4
5
6
7
8
9
10
l1 = [1, '1', True]
print(all(l1))

l2 = [0, '1', True]
print(all(l2))

------------
True
False
#0为假,可迭代对象中只要全为真才返回为真

相当于做了如下操作:

1
2
3
4
5
def all(iterable):
for element in iterable:
if not element:
return False
return True

any(iterable)

any函数接收一个可迭代的对象作为参数,只要有一个元素为真即返回为真

1
2
3
4
5
6
7
8
9
10
11
12
13
l1 = [1, '1', True]
print(any(l1))

l2 = [0, '1', True]
print(any(l2))

l3 = [0, '', False]
print(any(l3))

-----------
True
True
False

相当于做了如下操作:

1
2
3
4
5
def any(iterable):
for element in iterable:
if element:
return True
return False

all(iterable) 与 any(iterable) 的区别

  • all(iterable) 可迭代的参数对象中,只要有一个值为假,则立即返回False,所有值都为真才返回为True
  • any(iterable) 可迭代的参数对象中,只要有一个值为真,则立即返回True,所有值都为假才返回False

ascii(object)

ascii 自动执行对象的__repr__方法

这个函数跟repr()函数一样,返回一个可打印的对象字符串方式表示。

当遇到非ASCII码时,就会输出\x \u\U等字符来表示。

与Python 2版本里的repr()是等效的函数

1
2
3
4
5
6
7
8
class c():
def __repr__(self):
return 'repr'

print(ascii(c()))

------------
repr
1
2
3
4
>>> ascii('极地瑞雪')
"'\\u6781\\u5730\\u745e\\u96ea'"
>>> ascii('Polar Snow')
"'Polar Snow'"

repr(object)

而repr(object)转化为供解释器读取的字符串形式

1
2
3
4
>>> repr('极地瑞雪')
"'极地瑞雪'"
>>> repr('Polar Snow')
"'Polar Snow'"

str(object=’’)

class str(object=b’’, encoding=’utf-8’, errors=’strict’)

函数str(object=’’)用于将值转化为适于阅读的字符串形式

1
2
3
4
>>> str('极地瑞雪')
'极地瑞雪'
>>> str('Polar Snow')
'Polar Snow'

ascii(object) 与 repr(object) 的区别

两者的作用都是将对象转化为字符串

  • ascii()方法返回的字符串为非ascii码能表示的字符时,使用\x, \u or \U来表示
  • repr()方法返回对Python解释器友好的字符串格式
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> ascii('极地瑞雪')
"'\\u6781\\u5730\\u745e\\u96ea'"
>>> ascii('Polar Snow')
"'Polar Snow'"
>>> ascii(59)
'59'
------------
>>> repr('极地瑞雪')
"'极地瑞雪'"
>>> repr('Polar Snow')
>>> "'Polar Snow'"
>>> repr(59)
'59'

repr(object) 与 str(object=’’) 的区别

两者的作用都是将对象转化为字符串

  • repr()方法返回对Python解释器友好的字符串格式
  • str()方法返回对人阅读友好的字符串格式
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> repr('极地瑞雪')
"'极地瑞雪'"
>>> repr('Polar Snow')
>>> "'Polar Snow'"
>>> repr(59)
'59'
------------
>>> str('极地瑞雪')
'极地瑞雪'
>>> str('Polar Snow')
'Polar Snow'
>>> str(59)
'59'

bin(x)

bin(x) 接收一个十进制,返回二进制 0b

1
2
>>> bin(59)
'0b111011'

oct(x)

oct(x) 接收一个十进制,返回八进制 0o

1
2
>>> oct(59)
'0o73'

hex(x)

hex(x) 接收一个十进制,返回十六进制 0x

1
2
>>> hex(59)
'0x3b'

bool([x])

bool([x]) 判断元素真假, 以下元素为常出现的假元素:

  • 0
  • ‘’
  • []
  • ()
  • {}
  • set()
  • False

bytes

betes() 把指定的字符串转换为字节类型

1
2
3
4
5
6
7
8
9
>>> bytes('极地瑞雪', encoding='utf-8')
b'\xe6\x9e\x81\xe5\x9c\xb0\xe7\x91\x9e\xe9\x9b\xaa'
>>> str(b'\xe6\x9e\x81\xe5\x9c\xb0\xe7\x91\x9e\xe9\x9b\xaa', encoding='utf-8')
'极地瑞雪'
------------
>>> bytes('极地瑞雪', encoding='gbk')
b'\xbc\xab\xb5\xd8\xc8\xf0\xd1\xa9'
>>> str(b'\xbc\xab\xb5\xd8\xc8\xf0\xd1\xa9', encoding='gbk')
'极地瑞雪'

一个汉字使用utf-8编码的话占用三个字节,使用gbk编码的话占用两个字节

  • 打开文件乱码实况再现:
1
2
3
4
5
6
u = bytes('吕瑞', encoding='utf-8')
s = str(u, encoding='gbk')
print(s)

######运行结果
鍚曠憺

如果一个文件是以utf-8的编码方式保存,每三个字节是一个汉字,再同样以utf-8的方式读取,会正确的按照3个字节一个汉字去读取文件,而如果以gbk的方式读取文件,会按照两个字节一个汉字的方式读取,所以会产生乱码的情况

1
2
3
4
5
6
                        极地瑞雪(UTF-8)
二进制: 11100110 10011110 10000001 11100101 10011100 10110000 11100111 10010001 10011110 11101001 10011011 10101010
十进制: 230 158 129 229 156 176 231 145 158 233 155 170
十六进制: e6 9e 81 e5 9c b0 e7 91 9e e9 9b aa

注意:二进制的表现形式为字节
  • 用香来表示精确数字的小故事(二进制转十进制)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
一支香有两种状态,点燃的情况和熄灭的情况
现在定义:香熄灭[I]的状态表示0,点燃[i]的情况表示为1
0: 那么我现在要表示0,很简单,一支香足够,熄灭就行了--[I]
0
1: 一支香足够,点燃即可--[i]
1
2: 一支香最多只能表示到1,如果要表示2,需要在前面加一支香来表示2,这样我只需点燃头一支香即可表示2--[iI]
10
3: 两支香的话,第一支表示2,第一支最多表示1,只需将第二支点燃即可表示3--[ii]
11
4: 两支香最大可表示到3,现在需要加第三支香来表示4--[iII]
100
5: 以此类推--[iIi]
101


关系图:
最大表示:1
0: [I]
状态:0
-------------------
最大表示:1
1: [i]
状态:1
-------------------
最大表示:2 1
2: [i I]
状态:1 0
-------------------
最大表示:2 1
3: [i i]
状态:1 1
-------------------
最大表示:4 2 1
4: [i I I]
状态:1 0 0
-------------------
最大表示:4 2 1
5: [i I i]
状态:1 0 1
-------------------
最大表示:4 2 1
6: [i i I]
状态:1 1 0
-------------------
最大表示:4 2 1
7: [i i i]
状态:1 1 1
-------------------
最大表示:8 4 2 1
8: [i I I I]
状态:1 0 0 0
-------------------
最大表示:8 4 2 1
9: [i I I i]
状态:1 0 0 1
-------------------
最大表示:8 4 2 1
10: [i I i I]
状态:1 0 1 0
-------------------
最大表示:8 4 2 1
11: [i I i i]
状态:1 0 1 1
-------------------
最大表示:8 4 2 1
12: [i i I I]
状态:1 1 0 0
-------------------
最大表示:8 4 2 1
13: [i i I i]
状态:1 1 0 1
-------------------
最大表示:8 4 2 1
14: [i i i I]
状态:1 1 1 0
-------------------
最大表示:8 4 2 1
15: [i i i i]
状态:1 1 1 1
-------------------
最大表示:16 8 4 2 1
16: [i I I I I]
状态:1 0 0 0 0
-------------------
……以此类推
从2开始,每翻一番就多一支香来表示
4(2支),8(3支),16(4支)都增加了一支香类表示
32(5支),64(6支),128(7支),256(8支),512(9支),1024(10支)
也可以把"支"换成"2的x次方"--> 2的10次方=1024

callable(object)

callable(object) 检查对象是否可以被执行调用

1
2
3
4
5
6
7
8
9
10
11
12
13
def f1():
pass
# f1()

f2 = 123
# f2()

print(callable(f1))
print(callable(f2))

------------
True
False

chr(i)

chr(i) 将数字转换为字符

Python3中,chr() 不仅包含ascii的对照表,还包含了Unicode对照表

1
2
3
4
5
6
>>> chr(59)
';'
>>> chr(8364)
'€'
>>> chr(201559)
'\U00031357'

classmethod(function)

classmethod(function) 是一个装饰器函数,一般会使用@classmethod的方式来调用,用来表示下面的方法是类方法

1
2
3
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...

代码实例:参考自Pythontab

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> class C:
... @classmethod
... def f(cls):
... print "This is a class method"
...
>>> C.f()
This is a class method
>>> c = C()
>>> c.f()
This is a class method
>>> class D:
... def f(self):
... print " This is not a class method "
...
>>> D.f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with D instance as first argument (got nothing instead)
>>> d = D()
>>> d.f()
This is not a class method

staticmethod(function)

staticmethod(function) 是一个装饰器函数, 一般会使用@staticmethod的方式来调用,用来表示下面的方法的静态方法

1
2
3
class C:
@staticmethod
def f(arg1, arg2, ...): ...

classmethod(function) / staticmethod(function) 和实例方法的区别

实例的方法针对的是具体某一实例化对象的方法;类方法针对的是某一类的方法;静态方法可以与类或实例化无关

  • 类方法:
    • 类方法的第一个参数是class
    • 类方法可以通过类直接调用,不需要传递实例的引用
    • 默认将该class对象(不是class实例化对象)隐式的传递给方法
  • 静态方法:
    • 静态方法可以认为是全局函数
    • 静态方法可以用类调用,也可以用对象调用
    • 不会隐式的传入任何参数
  • 实例方法:
    • 实例方法的第一个参数是self
    • 实例方法必须通过实例化的对象去调用(Python3可以传递任意对象,Python2中会报错)
    • 默认将该实例化对象隐式的传递给方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Foo(object):
def test(self): #定义了实例方法
print("object")
@classmethod
def test2(clss): #定义了类方法
print("class")
@staticmethod
def test3(): #定义了静态方法
print("static")

# 实例方法的调用方式
# 第一种方式,先生成对象(先实例化)再调用
f1 = Foo()
f1.test()
# 第二种方式,自己传递实例的引用
Foo.test(f1)

# 类方法的调用方式
# 可以直接使用类来调用,不需要传递实例的引用
Foo.test2()

# 静态方法的调用方式
# 第一种方式,使用实例化对象来调用静态方法
f3 = Foo()
f3.test3()
# 第二种方式,使用类来调用静态方法
Foo.test3()

------------
object
object
class
static
static

代码实例:参考自ITEYE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Person:  

def __init__(self):
print "init"

@staticmethod
def sayHello(hello):
if not hello:
hello='hello'
print "i will sya %s" %hello


@classmethod
def introduce(clazz,hello):
clazz.sayHello(hello)
print "from introduce method"

def hello(self,hello):
self.sayHello(hello)
print "from hello method"


def main():
Person.sayHello("haha")
Person.introduce("hello world!")
#Person.hello("self.hello") #TypeError: unbound method hello() must be called with Person instance as first argument (got str instance instead)

print "*" * 20
p = Person()
p.sayHello("haha")
p.introduce("hello world!")
p.hello("self.hello")

if __name__=='__main__':
main()

------------
i will sya haha
i will sya hello world!
from introduce method
********************
init
i will sya haha
i will sya hello world!
from introduce method
i will sya self.hello
from hello method
```

---

# compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) 把字符串编译成Pythontab代码,编译后可以通过`eval()`或`exec()`来执行

```python
s = "print(123)"

# 编译,single,eval,exec
# 将字符串编译成python代码
r = compile(s, "<string>", "exec")

# 执行python代码
exec(r)

------------
123

print(123)'print(123)'的区别是,前者可以被Python解释器自动编译执行,而后者只是个字符串而已。如果想让后面的字符串去单过Python的命令的去执行,第一步就是先手动将该字符串进行编译,编译后的对象保存在内存中,可以被eval()exec()来执行

mode参数有三个:

  • single: 执行单条语句 —> exec()
  • exec: 可以执行多条语句 —> exec()
  • evel: 进行表达式计算 —> evel()

eval(expression, globals=None, locals=None)

eval(expression, globals=None, locals=None) 执行参数中的表达式并返回结果

1
2
3
>>> x = 1
>>> eval('x+1')
2

eval() 函数同样可以处理compile()函数生成的对象

1
2
3
4
5
6
7
8
9
print(eval('5 * 9'))

s = '5 * 9'
ret = compile(s, "<string>", 'eval')
print(eval(ret))

------------
45
45

exec(object[, globals[, locals]])

exec(object[, globals[, locals]]) 执行参数中的命令,返回值为None(区别于eval,eval是计算,计算就需要有返回值返回计算结果)

1
2
3
4
5
ret = exec('print(123)')
print(ret)

------------
None

exec() 函数处理compile()函数生成的对象—mod:single—处理单行命令

1
2
3
4
5
6
7
s = 'print(123)'
ret = compile(s, "<string>", 'single')
print(exec(ret)) #返回值为None

------------
123
None

exec() 函数处理compile()函数生成的对象—mod:single—处理多行命令

1
2
3
4
5
6
7
8
9
10
11
12
13
s = 'for i in range(5): print(i)'
ret = compile(s, "<string>", 'single')
print(exec(ret))

------------
Traceback (most recent call last):
File "/Users/lvrui/PycharmProjects/untitled/4/test.py", line 43, in <module>
ret = compile(s, "<string>", 'single')
File "<string>", line 1
for i in range(5): print(i)
^
SyntaxError: unexpected EOF while parsing
# single 模式无法处理多行命令,应该使用 exec模式

exec() 函数处理compile()函数生成的对象—mod:exec—处理多行命令

1
2
3
4
5
6
7
8
9
10
11
s = 'for i in range(5): print(i)'
ret = compile(s, "<string>", 'exec')
print(exec(ret)) #返回值为None

------------
0
1
2
3
4
None

代码实例:参考Pythoner

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> eval_code = compile( '1+2', '', 'eval')
>>> eval_code
<code object <module> at 0142ABF0, file "", line 1>
>>> eval(eval_code)
3

>>> single_code = compile( 'print "pythoner.com"', '', 'single' )
>>> single_code
<code object <module> at 01C68848, file "", line 1>
>>> exec(single_code)
pythoner.com

>>> exec_code = compile( """for i in range(5):
... print "iter time: %d" % i""", '', 'exec' )
>>> exec_code
<code object <module> at 01C68968, file "", line 1>
>>> exec(exec_code)
iter time: 0
iter time: 1
iter time: 2
iter time: 3
iter time: 4

Python反射相关

  • delattr()
  • hasattr()
  • getattr()
  • setattr()
  • __import__()

详细介绍请点击这里查看

未整理完的内建函数

  1. bytearray()
  2. complex()
  3. dict()
  4. dir()
  5. divmod()
  6. enumerate()
  7. filter()
  8. float()
  9. format()
  10. frozenset()
  11. globals()
  12. hash()
  13. help()
  14. id()
  15. input()
  16. int()
  17. isinstance()
  18. issubclass()
  19. iter()
  20. len()
  21. list()
  22. locals()
  23. map()
  24. max()
  25. memoryview()
  26. min()
  27. next()
  28. object()
  29. open()
  30. pow()
  31. print()
  32. property()
  33. range()
  34. reversed()
  35. round()
  36. set()
  37. slice()
  38. sorted()
  39. sum()
  40. super()
  41. tuple()
  42. type()
  43. vars()
  44. zip()