大数据 爬虫Python AI Sqlpython

腾讯十年Python开发经验总结的68个Python内置函数,是

2018-12-21  本文已影响2人  1a076099f916
腾讯十年Python开发经验总结的68个Python内置函数,是否对你有用

写在前面

入门Python其实很容易,但是我们要去坚持学习,每一天坚持很困难,我相信很多人学了一个星期就放弃了,为什么呢?其实没有好的学习资料给你去学习,你们是很难坚持的,这是小编收集的Python入门学习资料,加群:943752371就可以获取!希望对你们有帮助!

腾讯十年Python开发经验总结的68个Python内置函数,是否对你有用

一、内置函数

腾讯十年Python开发经验总结的68个Python内置函数,是否对你有用

10大类

1、数学运算(7个)

(1) abs()

(2) divmod()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>divmod(7, 2)
(3, 1)
</pre>

(3) max()

(4) min()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> min(-1,-2,key = abs) # 传入了求绝对值函数,则参数都会进行求绝对值后再取较小者
-1
</pre>

(5) pow()

(6) round()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">round(x[,n])
①使用math模块中的一些函数,比如math.ceiling(天花板除法)。
②python自带整除,//和div函数。
③字符串格式化可以做截断使用,例如"%.2f"% value(保留两位小数并变成字符串……如果还想用浮点数请披上float()的外衣)。
④当然,对浮点数精度要求如果很高的话,请用decimal模块。
</pre>

(7) sum()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>sum([0,1,2])
3

sum((2, 3, 4), 1) # 元组计算总和后再加 1
10
sum([0,1,2,3,4], 2) # 列表计算总和后再加 2
12
</pre>

2、类型转换(24个)

(1) bool()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>bool()
False

bool(0)
False
issubclass(bool, int) # bool 是 int 子类
True
</pre>

(2) int()

(3) float()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> float() #不提供参数的时候,返回0.0
0.0

float(3)
3.0
float('3')
3.0
</pre>

(4) complex()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">语法:class complex([real[, imag]])
参数:
real -- int, long, float或字符串
imag -- int, long, float

complex(1, 2)
(1 + 2j)
complex(1) # 数字
(1 + 0j)
complex("1") # 当做字符串处理
(1 + 0j)

注意:这个地方在"+"号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错

complex("1+2j")
(1 + 2j)
</pre>

(5) str()

(6) bytearry()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">class bytearray([source[, encoding[, errors]]])

如果 source 为整数,则返回一个长度为 source 的初始化数组;

如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列;

如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数;

如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。

如果没有输入任何参数,默认就是初始化数组为0个元素。

bytearray()
bytearray(b'')
bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
bytearray('中文','utf-8')
bytearray(b'\xe4\xb8\xad\xe6\x96\x87')
</pre>

(7) bytes()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> bytes('中文','utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
</pre>

(8) memoryview()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> v = memoryview(b'abcefg')

v[1]
98
v[-1]
103
</pre>

(9) ord()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>ord('a')
97

ord('€')
8364
</pre>

(10) chr()

(11) bin()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>bin(10)
'0b1010'

bin(20)
'0b10100'
</pre>

(12) oct()

(13) hex()

(14) tuple()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> tuple() #不传入参数,创建空元组
()

tuple('121') #传入可迭代对象,使用其元素创建新的元组
('1', '2', '1')
</pre>

(15) list()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>list() # 不传入参数,创建空列表
[]

list('abcd') # 传入可迭代对象,使用其元素创建新的列表
['a', 'b', 'c', 'd']
</pre>

(16) dict()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);"># 创建空字典

dict()
{}

传入关键字

dict(a='a', b='b', t='t')
{'a': 'a', 'b': 'b', 't': 't'}

映射函数方式来构造字典

dict(zip(['one', 'two', 'three'], [1, 2, 3]))
{'three': 3, 'two': 2, 'one': 1}

可迭代对象方式来构造字典

dict([('one', 1), ('two', 2), ('three', 3)])
{'three': 3, 'two': 2, 'one': 1}
</pre>

(17) set()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> a = set(range(10)) # 传入可迭代对象,创建集合

a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
x = set('runoob')
y = set('google')
x, y
(set(['b', 'r', 'u', 'o', 'n']), set(['e', 'o', 'g', 'l'])) # 重复的被删除
x & y # 交集
set(['o'])
x | y # 并集
set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
x - y # 差集
set(['r', 'b', 'u', 'n'])
</pre>

(18) frozenset()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>a = frozenset(range(10)) # 生成一个新的不可变集合

a

dict([('one', 1), ('two', 2), ('three', 3)])
{'three': 3, 'two': 2, 'one': 1}
</pre>

(17) set()

* 创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。语法: class set([iterable]) ,返回新的集合对象。

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> a = set(range(10)) # 传入可迭代对象,创建集合
>>> a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> x = set('runoob')
>>> y = set('google')
>>> x, y
(set(['b', 'r', 'u', 'o', 'n']), set(['e', 'o', 'g', 'l'])) # 重复的被删除
>>> x & y # 交集
set(['o'])
>>> x | y # 并集
set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
>>> x - y # 差集
set(['r', 'b', 'u', 'n'])
</pre>

(18) frozenset()

* 返回一个冻结的不可变集合,冻结后集合不能再添加或删除任何元素,语法: class frozenset([iterable])

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>a = frozenset(range(10)) # 生成一个新的不可变集合
>>> a
frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
b = frozenset('runoob')
b
frozenset(['b', 'r', 'u', 'o', 'n']) # 创建不可变集合
</pre>

(19) enumerate()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']

list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

指定起始值,小标从1开始

list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
普通for循环:
i = 0
seq = ['one', 'two', 'three']
for element in seq:
... print(i, seq[i])
... i += 1
for循环使用enumerate
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
... print(i, seq[i])
同样输出:
0 one
1 two
2 three
</pre>

(20) range()

(21) iter()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> a = iter('abcd') #字符串序列

a
<str_iterator object at 0x03FB4FB0>
next(a)
'a'
next(a)
'b'
next(a)
'c'
next(a)
'd'
next(a)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
next(a)
StopIteration
</pre>

(22) slice()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">语法:
class slice(stop)
class slice(start, stop[, step])

设置截取5个元素的切片

myslice = slice(5)
myslice
slice(None, 5, None)
arr = range(10)
arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

截取 5 个元素

arr[myslice]
[0, 1, 2, 3, 4]
</pre>

(23) super()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">语法:super(type[, object-or-type])

type -- 类。

object-or-type -- 类,一般是 self

class A:
pass
class B(A):
def add(self, x):
super().add(x)
</pre>

(24) object()

3、序列操作(8个)

(1) all()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> all(['a', 'b', '', 'd']) # 列表list,存在一个为空的元素
False

all([0, 1,2, 3]) # 列表list,存在一个为0的元素
False
all([]) # 空列表
True
all(()) # 空元组
True
</pre>

(2) any()

(3) filter()

(4) map()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>def square(x) : # 计算平方数
... return x ** 2

map(square, [1,2,3,4,5]) # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]

提供了两个列表,对相同位置的列表数据进行相加

map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
</pre>

(5) next()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> a = iter('abcd')

next(a)
'a'
next(a)
'b'
next(a)
'c'
next(a)
'd'
next(a)
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
next(a)
StopIteration
next(a,'e')
'e'
next(a,'e')
'e'
</pre>

(6) reversed()`` + 反转序列生成新的可迭代对象,语法: reversed(seq)`

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))
输出:
[5, 3, 4, 2, 1]
</pre>

(7) sorted()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">语法:sorted(iterable, key=None, reverse=False)

key主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序,reverse=True降序,reverse=False升序(默认)。

sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]

利用key进行倒序排序

example_list = [5, 0, 6, 1, 2, 7, 3, 4]
result_list = sorted(example_list, key=lambda x: x*-1)
print(result_list)
[7, 6, 5, 4, 3, 2, 1, 0]
</pre>

(8) zip()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> a = [1,2,3]

b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b) # 返回一个对象
zipped
<zip object at 0x103abc288>
list(zipped) # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
list(zip(a,c)) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]

a1, a2 = zip(zip(a,b)) # 与 zip 相反,zip() 可理解为解压,返回二维矩阵式
list(a1)
[1, 2, 3]
list(a2)
[4, 5, 6]
</pre>

4、对象操作(9个)

(1) help()

(2) dir()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> import math

math
<module 'math' (built-in)>
dir(math)
['doc', 'loader', 'name', 'package', 'spec', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
</pre>

(3) id()

(4) hash()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>hash('test') # 字符串
2314058222102390712

hash(1) # 数字
1
hash(str([1,2,3])) # 集合
1335416675971793195
hash(str(sorted({'1':1}))) # 字典
7666464346782421378
</pre>

(5) type()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">参数:
name -- 类的名称。
bases -- 基类的元组。
dict -- 字典,类内定义的命名空间变量。

使用type函数创建类型D,含有属性InfoD

D = type('D',(A,B),dict(InfoD='some thing defined in D'))
d = D()
d.InfoD
'some thing defined in D'
</pre>

(6) len()

(7) ascii()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>a = ascii('paul你好')

print(a)
'paul\u4f60\u597d'
</pre>

(8) format()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'

"{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))

通过字典设置参数

site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))

通过列表索引设置参数

my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须
输出:
网站名:菜鸟教程, 地址 www.runoob.com
class AssignValue(object):
def init(self, value):
self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value)) # "0" 是可选
</pre>

腾讯十年Python开发经验总结的68个Python内置函数,是否对你有用 腾讯十年Python开发经验总结的68个Python内置函数,是否对你有用

(9) vars()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>print(vars())
{'builtins': <module 'builtin' (built-in)>, 'name': 'main', 'doc': None, 'package': None}

class Runoob:
... a = 1
print(vars(Runoob))
{'a': 1, 'module': 'main', 'doc': None}
runoob = Runoob()
print(vars(runoob))
{}
</pre>

5、反射操作(8个)

(1) import()

(2) isinstance()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">type() 不会认为子类是一种父类类型,==不考虑继承关系==
isinstance() 会认为子类是一种父类类型,==考虑继承关系==
==如果要判断两个类型是否相同推荐使用isinstance()==

isinstance (a,(str,int,list)) # 是元组中的一个返回 True
True
class A:
pass

class B(A):
pass
isinstance(A(), A) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False
</pre>

(3) issubclass()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> issubclass(bool,int)
True

issubclass(bool,str)
False
issubclass(bool,(str,int))
True
</pre>

(4) hasattr()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> class Student:
def init(self,name):
self.name = name

s = Student('Aim')
hasattr(s,'name') #a含有name属性
True
hasattr(s,'age') #a不含有age属性
False
</pre>

(5) getattr()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>class A(object):
... bar = 1
...

a = A()
getattr(a, 'bar') # 获取属性 bar 值
1
getattr(a, 'bar2') # 属性bar2不存在,触发异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
getattr(a, 'bar2', 3) # 属性bar2不存在,但设置了默认值
3
</pre>

(6) setattr()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">语法:setattr(object, name, value) #(对象,字符串/对象属性,属性值)

class A(object):
... bar = 1
...
a = A()

获取属性 bar 值

getattr(a, 'bar')

s = Student('Aim')
>>> hasattr(s,'name') #a含有name属性
True
>>> hasattr(s,'age') #a不含有age属性
False
</pre>

(5) getattr()

* 获取对象的属性值。语法: getattr(object, name[, default])

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>class A(object):
... bar = 1
...
>>> a = A()
>>> getattr(a, 'bar') # 获取属性 bar 值
1
>>> getattr(a, 'bar2') # 属性bar2不存在,触发异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3) # 属性bar2不存在,但设置了默认值
3
</pre>

(6) setattr()

* 设置对象的属性值,前提是该属性必须存在。

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">语法:setattr(object, name, value) #(对象,字符串/对象属性,属性值)
>>>class A(object):
... bar = 1
...
>>> a = A()
# 获取属性 bar 值
>>> getattr(a, 'bar')
1

设置属性 bar 值

setattr(a, 'bar', 5)
a.bar
5
</pre>

(7) delattr()

(8) callable()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>> class B: #定义类B
def call(self):
print('instances are callable now.')

callable(B) #类B是可调用对象
True
b = B() #调用类B
callable(b) #实例b是可调用对象
True
b() #调用实例b成功
</pre>

6、变量操作(2个)

(1) globals()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>a='runoob'

print(globals())

globals 函数返回一个全局变量的字典,包括所有导入的变量。

{'builtins': <module 'builtin' (built-in)>, 'name': 'main', 'doc': None, 'a': 'runoob', 'package': None}
</pre>

(2) locals()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>def runoob(arg): # 两个局部变量:arg、z
... z = 1
... print (locals())
...

runoob(4)
{'z': 1, 'arg': 4} # 返回一个名字/值对的字典
</pre>

7、交互操作(2个)

(1) print()

(2) input()

8、文件操作(1个)

(1) open()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
file: 必需,文件路径(相对或者绝对路径)
mode: 可选,文件打开模式
buffering: 设置缓冲
encoding: 一般使用utf8
errors: 报错级别
newline: 区分换行符
closefd: 传入的file参数类型
opener:
</pre>

腾讯十年Python开发经验总结的68个Python内置函数,是否对你有用

9、编译执行(4个)

(1) compile()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">语法:compile(source, filename, mode[, flags[, dont_inherit]])
参数:
source -- 字符串或者AST(Abstract Syntax Trees)对象。。
filename -- 代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。
mode -- 指定编译代码的种类。可以指定为 exec, eval, single。
flags -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
flags和dont_inherit是用来控制编译源码时的标志

str = "for i in range(0,3): print(i)"
c = compile(str,'','exec') # 编译为字节代码对象
c
<code object <module> at 0x10141e0b0, file "", line 1>
exec(c)
0
1
2
str = "3 * 4 + 5"
a = compile(str,'','eval')
eval(a)
17
</pre>

(2) eval()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>x = 7

eval( '3 * x' )
21
eval('pow(2,2)')
4
eval('2 + 2')
4
n=81
eval("n + 4")
85
</pre>

(3) exec()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">x = 10
expr = """
z = 30
sum = x + y + z
print(sum)
"""
def func():
y = 20 # 局部变量y
exec(expr)
exec(expr, {'x': 1, 'y': 2})
exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})

在expr语句中,有三个变量x,y,z,其中z值已给定,我们可以在exec()函数外指定x,y的值,也可以在exec()函数中以字典的形式指定x,y的值。在最后的语句中,我们给出了x,y,z的值,并且y值重复,exec()函数接收后面一个y值,且z值传递不起作用,因此输出结果为34

func()
输出:
60
33
34
eval()函数和exec()函数的区别:
eval()函数只能计算单个表达式的值,而exec()函数可以动态运行代码段。
eval()函数可以有返回值,而exec()函数返回值永远为None。
</pre>

(4) repr()

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">>>>s = 'RUNOOB'

repr(s)
"'RUNOOB'"
dict = {'runoob': 'runoob.com', 'google': 'google.com'};
repr(dict)
"{'google': 'google.com', 'runoob': 'runoob.com'}"
</pre>

10、装饰器(3个)

(1) property

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">参数:
fget -- 获取属性值的函数
fset -- 设置属性值的函数
fdel -- 删除属性值函数
doc -- 属性描述信息

将 property 函数用作装饰器可以很方便的创建只读属性

class Parrot(object):
def init(self):
self._voltage = 100000

@property
def voltage(self):
"""Get the current voltage."""
return self._voltage

上面的代码将 voltage() 方法转化成同名只读属性的getter方法。property的getter,setter 和deleter方法同样可以用作装饰器:

class C(object):
def init(self):
self._x = None

@property
def x(self):
"""I'm the 'x' property."""
return self._x

@x.setter
def x(self, value):
self._x = value

@x.deleter
def x(self):
del self._x

class C:
def init(self):
self._name = ''
@property
def name(self):
"""i'm the 'name' property."""
return self._name
@name.setter
def name(self,value):
if value is None:
repr(s)
"'RUNOOB'"
>>> dict = {'runoob': 'runoob.com', 'google': 'google.com'};
>>> repr(dict)
"{'google': 'google.com', 'runoob': 'runoob.com'}"
</pre>

10、装饰器(3个)

(1) property

* 标示属性的装饰器 ,语法: class property([fget[, fset[, fdel[, doc]]]])

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">参数:
fget -- 获取属性值的函数
fset -- 设置属性值的函数
fdel -- 删除属性值函数
doc -- 属性描述信息
# 将 property 函数用作装饰器可以很方便的创建只读属性
class Parrot(object):
def init(self):
self._voltage = 100000

@property
def voltage(self):
"""Get the current voltage."""
return self._voltage

# 上面的代码将 voltage() 方法转化成同名只读属性的getter方法。property的getter,setter 和deleter方法同样可以用作装饰器:
class C(object):
def init(self):
self._x = None

@property
def x(self):
"""I'm the 'x' property."""
return self._x

@x.setter
def x(self, value):
self._x = value

@x.deleter
def x(self):
del self._x
>>> class C:
def init(self):
self._name = ''
@property
def name(self):
"""i'm the 'name' property."""
return self._name
@name.setter
def name(self,value):
if value is None:
raise RuntimeError('name can not be None')
else:
self._name = value

c = C()
c.name # 访问属性
''
c.name = None # 设置属性时进行验证
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
c.name = None
File "<pyshell#81>", line 11, in name
raise RuntimeError('name can not be None')
RuntimeError: name can not be None
c.name = 'Kim' # 设置属性
c.name # 访问属性
'Kim'
del c.name # 删除属性,不提供deleter则不能删除
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
del c.name
AttributeError: can't delete attribute
c.name
'Kim'
</pre>

(2) classmethod

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">class A(object):
bar = 1
def func1(self):
print ('foo')
@classmethod
def func2(cls):
print ('func2')
print (cls.bar)
cls().func1() # 调用 foo 方法

A.func2() # 不需要实例化
</pre>

(3) staticmethod

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);">class C(object):
@staticmethod
def f(arg1, arg2, ...):
pass

以上实例声明了静态方法f,类可以不用实例化就可以调用该方法C.f(),当然也可以实例化后调用C().f()。

class C(object):
@staticmethod
def f():
print('runoob');

C.f() # 静态方法无需实例化
cobj = C()
cobj.f() # 也可以实例化后调用

使用装饰器定义静态方法

class Student(object):
def init(self,name):
self.name = name
@staticmethod
def sayHello(lang):
print(lang)
if lang == 'en':
print('Welcome!')
else:
print('你好!')

Student.sayHello('en') #类调用,'en'传给了lang参数
en
Welcome!
b = Student('Kim')
b.sayHello('zh') #类实例对象调用,'zh'传给了lang参数
zh
你好
</pre>

腾讯十年Python开发经验总结的68个Python内置函数,是否对你有用
上一篇下一篇

猜你喜欢

热点阅读